Does Returning a Local Variable Return a Copy and Destroy the Original (NRVO)?
Introduction:
The question examines the behavior of returning a local variable in C . Specifically, it explores whether the returned object is a copy or the original object, and how it impacts the destruction of the local variable.
Return Value Optimization (NRVO):
With NRVO (named return value optimization) enabled, the compiler optimizes the return statement to avoid unnecessary copy construction or destruction of the local variable. It achieves this by directly constructing the return object into the target storage, eliminating the overhead of intermediate copies or moves. NRVO applies when specific conditions are met, such as the local variable having automatic storage duration and being of the same type as the return type.
Example with NRVO Enabled:
Consider the following code:
class Test { public: Test(int p) { std::cout << "Constructor called" << std::endl; } ~Test() { std::cout << "Destructor called" << std::endl; } }; Test function() { Test t(5); // local variable with automatic storage duration return t; // return local variable } int main() { Test o = function(); return 0; }
With NRVO enabled, the output will be:
Constructor called Destructor called
In this case, NRVO optimizes the return statement and constructs the object o directly into the storage for the local variable t. The constructor is called once, and only one destructor is called for the object o.
Example with NRVO Disabled:
However, NRVO can be disabled using the -fno-elide-constructors compiler flag. Without NRVO, the compiler will perform the copy construction and destruction steps explicitly.
Constructor called Constructor called Destructor called Destructor called
In this case, the constructor is called twice (for the local variable t and the return object o). Additionally, both the local variable t and the return object o are destructed separately.
Conclusion:
The behavior of returning a local variable depends on whether NRVO is enabled or disabled. With NRVO enabled, the local variable is optimized away, and the constructor and destructor are called only once for the return object. Without NRVO, the copy construction and destruction steps are performed explicitly, potentially invoking the constructor and destructor multiple times.
The above is the detailed content of Does Returning a Local Variable in C Utilize Named Return Value Optimization (NRVO) to Avoid Copy Construction and Destruction?. For more information, please follow other related articles on the PHP Chinese website!