Home > Backend Development > C++ > body text

How Does Named Return Value Optimization (NRVO) Affect Local Variable Return Behavior?

Barbara Streisand
Release: 2024-11-09 09:03:02
Original
779 people have browsed it

How Does Named Return Value Optimization (NRVO) Affect Local Variable Return Behavior?

Understanding the Return Behavior of Local Variables

When returning a local variable from a function, its behavior can vary depending on compiler optimizations.

NRVO (Named Return Value Optimization)

When NRVO is enabled, the compiler optimizes the return statement by creating the object being returned directly at the site of the return value. In this case, no copy is performed, and the original object is destroyed after the return.

Output with NRVO Enabled

// With NRVO enabled, only one constructor and destructor call is made.
class test {
public:
  test(int p) {
    std::cout << "Constructor (test(int p)) called\n";
  }

  ~test() {
    std::cout << "Destructor called\n";
  }
};

test function() {
  test i(8);
  return i;
}

int main() {
  test o = function();
  return 0;
}
Copy after login

Output:

Constructor (test(int p)) called
Destructor called
Copy after login

NRVO Disabled

To disable NRVO, use the -fno-elide-constructors flag during compilation. In this case, the compiler does not perform NRVO, and a copy of the object is created in the return value.

Output with NRVO Disabled

// With NRVO disabled, both constructor and destructor calls are made twice.
class test {
public:
  test(int p) {
    std::cout << "Constructor (test(int p)) called\n";
  }

  test(test&& other) {
    std::cout << "Constructor (test(test&& other)) called\n";
  }

  ~test() {
    std::cout << "Destructor called\n";
  }
};

test function() {
  test i(8);
  return i;
}

int main() {
  test o = function();
  return 0;
}
Copy after login

Output:

Constructor (test(int p)) called
Constructor (test(test&& other)) called
Destructor called
Destructor called
Copy after login

Summary

  • With NRVO enabled, returning a local variable eliminates the need for a copy, directly constructs the object at the return site, and destroys the original object immediately.
  • With NRVO disabled, a copy of the object is created and returned, resulting in two copies of the object.

The above is the detailed content of How Does Named Return Value Optimization (NRVO) Affect Local Variable Return Behavior?. 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