C++ new operator scope
So I was writing a piece of code where I used new operator to create an object inside a local scope function and returned the reference as a pointer.
A* operator+(A that){
int sumA = a + that.getA();
int sumB = b + that.getB();
return new A(sumA, sumB);
}
In my thought It would not work because the object was created inside the local scope and should be temporary, but it compiled and ran. Can anyone explain to me about this? I am sure there are other things that kinda have the ability of breaking the scope and stuff.. If possible, could you give me some examples? Appreciated!
When you say "created inside local scope" what you really mean is "an automatic variable." Automatic variables are automatically destroyed when the scope in which they are created is exited from.
But new
does not create an automatic variable. It creates a dynamically allocated object, whose lifetime is not bound by the scope in which it's created.
The object created by, new A(sumA, sumB)
is not a temporary.
Values are returned from a local scope all the time. For example:
int f(int x)
{
int y = x*x;
return y;
}
While a variable would normally disappear when it falls out of scope, values returned from functions get special treatment by the compiler.
Regarding your example, you are creating an object on the heap and have a pointer to that object on the local stack. When your function returns the stack is cleaned up, that pointer along with it. Except - since you're returning the pointer to the caller, a copy of the pointer is passed back to the caller (probably through a cpu register).
As an aside: While this works fine, you need to be certain that the caller eventually deletes the returned object, else you'll have a memory leak.
C++ does not automatically manage memory for you. This means you must manually 'delete' any objects created dynamically with the 'new' operator. Your code is valid, but I think it doesn't accomplish what you wish. I think you are looking for something like this:
A operator+(const A& that){
int sumA = a + that.getA();
int sumB = b + that.getB();
return A(sumA, sumB);
}
链接地址: http://www.djcxy.com/p/96548.html
上一篇: $ total = 0和var $ total = 0.哪一个是正确的?
下一篇: C ++新的运营商范围