临时对象的取消引用运算符

Dereference operator on temporary object

在这样的代码中

#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());
}

是否保证A对象只有在f()执行后才会被删除?

是的,没错。 C++ 标准明确规定所有作为函数参数传递的匿名临时对象在函数调用后仍然存在。

对象将在计算完整表达式后被删除 f(*make_a());

是的,保证 temporary 在完整表达式之后被销毁,其中包括函数 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.

临时对象在完整表达式结束后被销毁。

在你的例子中,完整表达式f(*make_a()),这意味着一旦对f的调用完成(在函数 f 已返回)。

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

C++ 标准保证所有临时对象一直存在到 完整表达式 (以分号 ; 结尾的表达式)的计算结束。有关详细信息,请参阅 Lifetime

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.