Home > Backend Development > C++ > Does Returning a Local Variable by Value Destroy the Original Object?

Does Returning a Local Variable by Value Destroy the Original Object?

DDD
Release: 2024-11-09 13:15:02
Original
826 people have browsed it

Does Returning a Local Variable by Value Destroy the Original Object?

Copy Elision and Object Lifetime

When returning a local variable by value, one may wonder whether the original object is destroyed or not. The answer lies in understanding copy elision.

With Copy Elision (NRVO)

When optimization (known as Named Return Value Optimization or NRVO) is enabled, the compiler may optimize the return statement by constructing the object directly into the storage where it would otherwise be copied to. As a result, the original object is not created in the first place.

Example with NRVO Enabled

Consider the following code:

class Test {
public:
    Test(int p) { cout << "Constructor called" << endl; }
    ~Test() { cout << "Destructor called" << endl; }
};

Test function() {
    Test t(5);
    return t;
}

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

With NRVO enabled, the output will be:

Constructor called
Destructor called
Copy after login

Only the object o is constructed and destroyed, and the original object t is optimized away.

Without Copy Elision

When optimization is disabled (e.g., -fno-elide-constructors), the return statement will follow the usual copy/move semantics.

Example with NRVO Disabled

Using the code from above with NRVO disabled, the output will be:

Constructor called
Constructor called
Destructor called
Destructor called
Copy after login

This time, both objects t and o are constructed and destroyed, as the copy/move construction cannot be optimized away.

Conclusion

Whether returning a local variable by value destroys the original object depends on whether NRVO is enabled or not. With NRVO, the original object may be elided, while without NRVO, it will be copied/moved as per standard copy/move semantics.

The above is the detailed content of Does Returning a Local Variable by Value Destroy the Original Object?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template