2

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
tmlen
  • 8,533
  • 5
  • 31
  • 84

5 Answers5

6

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
5

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.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
4

Yes that's correct. The C++ standard states clearly that all anonymous temporaries passed as function parameters survive the function call.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
4

The object will be deleted after evaluation of the full expression f(*make_a());

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
4

Temporary objects are destructed once the full expression they're involved in ends.

In your case the full expression is f(*make_a()), which means that the object will be destructed once the call to f is finished (after the function f have returned).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621