问题
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!
回答1:
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.
回答2:
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.
回答3:
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);
}
回答4:
Yes, the value created with new
will still be alive after the function exits.
As others have mentioned, it is necessary to delete
these objects to avoid memory leaks.
Because of this, best general C++ practice is to not return bare pointers like this function does, but to return some sort of smart pointer object such as shared_ptr
. That way, you can return a pointer to the newly created object, and the object will be automatically destroyed once there are no more active references to it.
来源:https://stackoverflow.com/questions/23508156/c-new-operator-scope