gpt4 book ai didi

c++ - 引用 const 临时对象的意外行为

转载 作者:行者123 更新时间:2023-11-28 06:35:39 25 4
gpt4 key购买 nike

以下代码在 Visual Studio 2013 中编译时没有任何警告。删除最后一行中的注释将不会编译。这是 Visual Studio 2013 中的错误吗?如果不是,我应该如何在标准中理解它?

我认为允许引用临时对象是非常危险的,不是吗?

struct A
{
string a;

void f( const string & toMove )
{
a = toMove;
}
void g( string & toMove )
{
a = toMove;
}
} aa;

stringstream d_SS;
d_SS << "A string";
aa.f( d_SS.str() );
//aa.g( d_SS.str() );

编辑

在此related question ,他们解释说“不允许获得对临时对象的非常量引用”。那么我的问题是为什么我们被允许以 aa.f( d_SS.str() ) 的方式获取对临时对象的 const 引用。 d_SS.str() 在进入函数体之前就死了!

最佳答案

d_SS.str() is dead before it enters to the body of function!

不正确;它仍然存在,直到当前 full-expression 结束,在本例中是 aa.f( d_SS.str() ); 末尾的分号.

只有当 aa.f 获取指向其参数的引用或指针并将其保存到某个外部数据区域时才会有危险。 aa.f 只读取它的参数是完全安全的。

关于c++ - 引用 const 临时对象的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26825810/

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