Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereference operator on temporary object

In a code like this

#include <iostream>
#include <memory>

struct A {
    int i;

    A() {
        std::cout << "A()" << std::endl;
    }

    ~A() {
        std::cout << "~A()" << std::endl;
    }
};

void f(const A& a) {
    std::cout << "f(A)" << std::endl;
}

std::unique_ptr<A> make_a() {
    return std::make_unique<A>();
}

int main() {
    f(*make_a());
}

Is there a guarantee that the A object will be deleted only after f() was executed?

like image 813
tmlen Avatar asked Mar 08 '26 20:03

tmlen


1 Answers

Yes, it's guaranteed that the temporary will be destroyed after the full-expression, which includes the invocation of the function f().

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception.

like image 73
songyuanyao Avatar answered Mar 11 '26 10:03

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!