c++destructortemporary-objectsfull-expression

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?


Solution

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

    The C++ standard guarantees that all temporary objects live till then end of evaluating of the full expression (the one that ends with a semi-colon ;). See Lifetime for full details:

    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.