gpt4 book ai didi

c++ - 返回原始类型和结构的本地对象

转载 作者:行者123 更新时间:2023-11-30 03:45:08 25 4
gpt4 key购买 nike

获取对临时变量的引用:

struct S
{
S() = default;
S(const S& other) = delete;
S(S&& other) = delete;

~S(){}
};

S foo1()
{
return {}; // RVO (???)
}

int foo2()
{
return 42; // RVO
}

int main()
{
S& i = foo1(); // compiles!
int& i2 = foo3(); // error C2440: 'initializing' : cannot convert from 'int' to 'int &'
}

我知道使用 const 说明符可以延长引用生命周期。并且很清楚为什么 foo2 会出错。但为什么 foo1 有效?

P.S.: 使用 VS2013/15 测试

最佳答案

在启用所有警告的情况下编译 (/Wall),您会偶然得到以下内容:

source_file.cpp(22): warning C4239: nonstandard extension used: 'initializing': conversion from 'S' to 'S &'

关于c++ - 返回原始类型和结构的本地对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35040376/

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