Does Returning a Local Variable Return a Copy and Destroy the Original (NRVO)?
In C 17, when optimization is enabled (specifically, named return value optimization or NRVO), returning a local variable doesn't involve copying the original object. Instead, the compiler optimizes the code to construct the returned object directly into the storage where it would otherwise be copied. This means that the original object is effectively moved to the return value location, and no destructors are called.
However, if optimization is disabled (using the -fno-elide-constructors flag), the default behavior is followed:
In the code you provided:
test function() { test i(8); return i; }
With NRVO enabled, only one constructor and destructor call are observed, indicating that the original i object is moved to the return value location without copying.
With NRVO disabled, both constructor and destructor calls are observed for both the original i object and the return value object, indicating that the original i object is copied and then destructed.
Therefore, the answer to your question depends on whether or not optimization is enabled. With NRVO enabled, returning a local variable doesn't return a copy and doesn't destroy the original. With NRVO disabled, it returns a copy and destroys the original.
The above is the detailed content of Does Returning a Local Variable in C 17 Return a Copy and Destroy the Original (NRVO)?. For more information, please follow other related articles on the PHP Chinese website!