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::coutWith NRVO enabled, the output will be:
Constructor called Destructor calledIn 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 calledIn 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3