不是最重要的常量..但这是什么?
这输出 F~
但我期待 ~F
#include <iostream>
struct Foo {
int _x;
operator const int & () const {return _x;}
~ Foo () {std :: cout << "~";}
};
void foo (const int &)
{
std :: cout << "F";
}
int main ()
{
foo (Foo ());
}
我将其构建为反例,以表明最重要的常量是一个例外而不是规则。通常写为
当 const 引用绑定到临时对象时,该临时对象的生命周期将延长到引用的生命周期
我试图说明的是,虽然 Foo() 是一个临时对象,但对 的引用>_x
返回的转换运算符不是,说明上面的代码是不安全的。
但输出似乎证明该示例是安全的,临时 Foo()
的生命周期因对其成员之一的 const 引用的存在而延长。
这是对的吗?标准中哪里规定了这一点?
This outputs F~
but I was expecting ~F
#include <iostream>
struct Foo {
int _x;
operator const int & () const {return _x;}
~ Foo () {std :: cout << "~";}
};
void foo (const int &)
{
std :: cout << "F";
}
int main ()
{
foo (Foo ());
}
I constructed this as a counterexample to show that the most-important-const is an exception rather than a rule. It is normally written as
when a const reference binds to a temporary, then the lifetime of that temporary is extended to the lifetime of the reference
I was trying to illustrate that, although Foo()
is a temporary, the reference to _x
returned by the conversion operator is not, and that the above code is unsafe.
But the output seems to prove that the example is safe, the lifetime of the temporary Foo()
is extended by the existence of a const reference to one of its members.
Is this right? Where in the standard is this specified?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
关于临时对象的一般规则是,当它们成为结束的完整表达式的一部分时(非正式地,当到达
;
时),它们的生命就结束了。The general rule, regarding temporaries, is that their life ends when the full expression they are part of ends (informally, when reaching the
;
).这是因为临时变量在函数调用的整个过程中都存在。当您执行
foo (Foo ());
时,会发生以下情况:Foo
被构造,然后operator const int&
foo()
返回,foo()
被调用,并且输出F
,Foo
被销毁,并且输出 <代码>~That's because the temporary survives for the whole duration of function call. When you do
foo (Foo ());
here's what happens:Foo
is contructed, thenoperator const int&
is called on the temporaryfoo()
is called and this outputsF
foo()
returns temporaryFoo
is destroyed and this outputs~
这里没有魔法。所有函数参数都位于调用者的范围内,包括临时参数。临时
Foo()
在调用者的范围内构造,并在行尾销毁。因此,无论函数
foo()
做什么,都发生在main()
中的参数被销毁之前。There's no magic here. All function arguments live in the scope of the caller, including temporaries. The temporary
Foo()
is constructed in the scope of the caller, and destroyed at the end of the line.So whatever the function
foo()
does happens before its arguments inmain()
are destroyed.但是这里的
Foo
实例始终会存在,直到分号结束创建它的语句为止。将对成员的引用传递到函数调用中并没有改变这一点。尝试:
对比
But your
Foo
instance here was always going to live until the semicolon ending the statement in which it was created. Passing a reference to a member into a function call didn't change that.Try:
versus