gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:57:27 27 4
gpt4 key购买 nike

我想知道标准对下面这段代码的看法。临时对象的string析构函数能否在调用printPointer之前执行?

附注VS2010 编译器不会提示此代码并且可以正常工作。

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

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

int main()
{
printPointer(func("Hello, World!!!"));
}

最佳答案

Can string destructor of temporary object be executed before calling printPointer?

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

来自标准#12.2/4 Temporary objects[class.temporary] :

Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created.

#12.2/6 Temporary objects[class.temporary] :

A temporary object bound to a reference parameter in a function call ([expr.call]) persists until the completion of the full-expression containing the call.

explanatory demo

关于c++ - 函数调用中的隐式析构函数执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38345484/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com