Does Returning a Local Variable Destroy the Original?
In C 17 onwards, whether returning a local variable returns a copy or destroys the original depends on whether optimization is enabled.
With Optimization (NRVO)
With optimization enabled (known as named return value optimization or NRVO), the compiler can directly construct the returned object into the storage where it would be copied/moved to. This means the original local variable is not destroyed.
Without Optimization
If optimization is disabled (using -fno-elide-constructors), NRVO is disabled. The local variable will be constructed normally, a copy or move will be performed, and the original will be destroyed.
Example
Consider the following code:
class test { public: test(int p) { cout << "Constructor: " << this << endl; } test(test&& c) noexcept { cout << "Move Constructor: " << this << endl; } ~test() { cout << "Destructor: " << this << endl; } }; test function() { test i(8); return i; }
Output with Optimization (NRVO):
Constructor: 0x7fff78e42887 Destructor: 0x7fff78e42887
Output without Optimization:
Constructor: 0x7ffda9d94fe7 Move Constructor: 0x7ffda9d95007 Destructor: 0x7ffda9d94fe7 Destructor: 0x7ffda9d95007
In the optimized case, only one object is constructed and destroyed. In the unoptimized case, two objects are constructed and destroyed due to a temporary copy being made.
The above is the detailed content of Does Returning a Local Variable in C 17 Destroy the Original?. For more information, please follow other related articles on the PHP Chinese website!