C++:被忽略的 return 值破坏行为是否定义明确
C++: Is the ignored return value destruction behavior well-defined
问题: 被忽略的 return 值是立即销毁还是正在超出范围?
下面的代码 returns 用于我的编译器
输出:
Who makes it, has no need of it.
Who buys it, has no use for it.
Who uses it can neither see nor feel it.
What is it?
因此被忽略的值被立即销毁。但是这个编译器是特定的还是标准的行为?
struct foo
{
~foo()
{
std::cout << "Who makes it, has no need of it. \n"
<< "Who buys it, has no use for it. \n";
}
}
foo createFoo()
{
return foo();
}
int main(int argc, char* argv[])
{
createFoo();
std::cout << "Who uses it can neither see nor feel it.\n"
<< "What is it?";
}
如果通过绑定到右值或 const 左值引用来延长其生命周期,则返回的临时值会在完整表达式完成后立即销毁 。
在标准5.11中有
In some contexts, an expression only appears for its side effects. Such an expression is called a discarded-value
expression. The expression is evaluated and its value is discarded.
因此,当表达式结束时,该值将被丢弃,如果它是 class 类型,则调用析构函数。
Temporary objects are destroyed as the last step
in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying
a temporary object are associated only with the full-expression, not with any specific subexpression.
异常是针对构造函数参数和对临时对象的绑定引用。 (§12.3/4f.)
问题: 被忽略的 return 值是立即销毁还是正在超出范围?
下面的代码 returns 用于我的编译器
输出:
Who makes it, has no need of it.
Who buys it, has no use for it.
Who uses it can neither see nor feel it.
What is it?
因此被忽略的值被立即销毁。但是这个编译器是特定的还是标准的行为?
struct foo
{
~foo()
{
std::cout << "Who makes it, has no need of it. \n"
<< "Who buys it, has no use for it. \n";
}
}
foo createFoo()
{
return foo();
}
int main(int argc, char* argv[])
{
createFoo();
std::cout << "Who uses it can neither see nor feel it.\n"
<< "What is it?";
}
如果通过绑定到右值或 const 左值引用来延长其生命周期,则返回的临时值会在完整表达式完成后立即销毁 。
在标准5.11中有
In some contexts, an expression only appears for its side effects. Such an expression is called a discarded-value expression. The expression is evaluated and its value is discarded.
因此,当表达式结束时,该值将被丢弃,如果它是 class 类型,则调用析构函数。
Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.
异常是针对构造函数参数和对临时对象的绑定引用。 (§12.3/4f.)