函数调用中的隐式析构函数执行

ska*_*kap 8 c++ destructor temporary object-lifetime language-lawyer

我想知道关于下面这段代码的标准是什么.可以string临时对象的析构函数调用之前执行printPointer

ps VS2010编译器不会抱怨此代码并且工作正常.

void printPointer(const string* pointer)
{
    cout << *pointer << endl;
}

const string* func(const string& s1)
{
    return &s1;
}

int main()
{
    printPointer(func("Hello, World!!!"));
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 9

可以string临时对象的析构函数调用之前执行printPointer

不,因为临时对象将作为评估包含创建它们的点的完整表达式的最后一步被销毁,这意味着它将持续到调用printPointer()结束.

从标准#12.2/4临时对象[class.temporary]:

临时对象作为评估完整表达式([intro.execution])的最后一步被销毁,该表达式(词法上)包含创建它们的点.

#12.2/6临时对象[class.temporary]:

绑定到函数调用([expr.call])中的引用参数的临时对象将持续存在,直到包含该调用的完整表达式完成.

explanatory demo