Home  >  Article  >  Backend Development  >  Does Returning a Local Variable in C 17 Destroy the Original?

Does Returning a Local Variable in C 17 Destroy the Original?

DDD
DDDOriginal
2024-11-11 11:22:03862browse

Does Returning a Local Variable in C  17 Destroy the Original?

Does Returning a Local Variable Destroy the Original?

In C 17 onwards, whether returning a local variable returns a copy or destroys the original depends on whether optimization is enabled.

With Optimization (NRVO)

With optimization enabled (known as named return value optimization or NRVO), the compiler can directly construct the returned object into the storage where it would be copied/moved to. This means the original local variable is not destroyed.

Without Optimization

If optimization is disabled (using -fno-elide-constructors), NRVO is disabled. The local variable will be constructed normally, a copy or move will be performed, and the original will be destroyed.

Example

Consider the following code:

class test {
public:
    test(int p) { cout << "Constructor: " << this << endl; }
    test(test&& c) noexcept { cout << "Move Constructor: " << this << endl; }
    ~test() { cout << "Destructor: " << this << endl; }
};

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

Output with Optimization (NRVO):

Constructor: 0x7fff78e42887
Destructor: 0x7fff78e42887

Output without Optimization:

Constructor: 0x7ffda9d94fe7
Move Constructor: 0x7ffda9d95007
Destructor: 0x7ffda9d94fe7
Destructor: 0x7ffda9d95007

In the optimized case, only one object is constructed and destroyed. In the unoptimized case, two objects are constructed and destroyed due to a temporary copy being made.

The above is the detailed content of Does Returning a Local Variable in C 17 Destroy the Original?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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