[英]C++ temporary object's lifetime
void foo(const C &);
foo(C());
In this case, temporary C
object lives until the end of foo()
. 在这种情况下,临时
C
对象将保留到foo()
结束。
But my question is: 但是我的问题是:
struct C { operator int(); }
void bar(int i);
bar(C());
In that case, Does temporary C
object live until the end of bar()
? 在这种情况下,临时
C
对象是否生存到bar()
的末尾? If not, Is there any way to make temporary object live until the end of bar()
? 如果不是,是否有任何方法可以使临时对象存活到
bar()
结束?
edit: Thanks to user2109558, I know the code doesn't work. 编辑:感谢user2109558,我知道代码不起作用。 Then does the following code work well?
那么下面的代码工作正常吗?
void bar(int i);
void bar(C &&c) { bar(c); }
No!the code bar(C());
不!代码
bar(C());
is equal to int num = C(); bar(num);
等于
int num = C(); bar(num);
int num = C(); bar(num);
So , temporary C object does not live until the end of bar() you have to change bar
function parameter.such as void bar(const C &)
or add global C object variable eg: 因此,临时C对象直到bar()结束才存在,您必须更改
bar
函数参数。例如void bar(const C &)
或添加全局C对象变量,例如:
C c;
void bar(int i) {
.....
} }
but no suggestion do it. 但没有建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.