Copy Elision and Object Lifetime
When returning a local variable by value, one may wonder whether the original object is destroyed or not. The answer lies in understanding copy elision.
With Copy Elision (NRVO)
When optimization (known as Named Return Value Optimization or NRVO) is enabled, the compiler may optimize the return statement by constructing the object directly into the storage where it would otherwise be copied to. As a result, the original object is not created in the first place.
Example with NRVO Enabled
Consider the following code:
class Test { public: Test(int p) { cout << "Constructor called" << endl; } ~Test() { cout << "Destructor called" << endl; } }; Test function() { Test t(5); return t; } int main() { Test o = function(); return 0; }
With NRVO enabled, the output will be:
Constructor called Destructor called
Only the object o is constructed and destroyed, and the original object t is optimized away.
Without Copy Elision
When optimization is disabled (e.g., -fno-elide-constructors), the return statement will follow the usual copy/move semantics.
Example with NRVO Disabled
Using the code from above with NRVO disabled, the output will be:
Constructor called Constructor called Destructor called Destructor called
This time, both objects t and o are constructed and destroyed, as the copy/move construction cannot be optimized away.
Conclusion
Whether returning a local variable by value destroys the original object depends on whether NRVO is enabled or not. With NRVO, the original object may be elided, while without NRVO, it will be copied/moved as per standard copy/move semantics.
The above is the detailed content of Does Returning a Local Variable by Value Destroy the Original Object?. For more information, please follow other related articles on the PHP Chinese website!