Home > Backend Development > C++ > Does Returning a Local Variable in C 17 Return a Copy and Destroy the Original (NRVO)?

Does Returning a Local Variable in C 17 Return a Copy and Destroy the Original (NRVO)?

Mary-Kate Olsen
Release: 2024-11-22 06:50:15
Original
442 people have browsed it

Does Returning a Local Variable in C  17 Return a Copy and Destroy the Original (NRVO)?

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:

  • The local variable is constructed normally.
  • The local variable is then moved or copied (depending on its moveability) to the return value location.
  • The original local variable is destructed.

In the code you provided:

test function() {
    test i(8);
    return i;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template