Nav*_*K N 8 c++ return-value-optimization
请考虑以下代码,
struct foo
{
foo()
{
std::cout << "Constructing!" << std::endl;
}
foo(const foo& f)
{
std::cout << "Copy constructing!" << std::endl;
}
~foo()
{
std::cout << "Destructing.." << std::endl;
}
};
foo get()
{
foo f;
return f;
}
int main()
{
const foo& f = get();
std::cout << "before return" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
MSVC上的输出
Constructing!
Copy constructing!
Destructing..
before return
Destructing..
Run Code Online (Sandbox Code Playgroud)
GCC的产出
Constructing!
before return
Destructing..
Run Code Online (Sandbox Code Playgroud)
MSVC上的结果看起来不正确.
问题
const foo& f = get()并且const foo f = get()由于返回值优化而产生相同的输出.在这种情况下,应该首选哪种写作方式?有什么想法吗..
GMa*_*ckG 11
您的MSVC构建没有优化.打开它们,你会得到相同的输出.
默认情况下,GCC仅对您的临时执行RVO.它基本上是这样做的:
const foo& f = foo();
Run Code Online (Sandbox Code Playgroud)
MSVC不是.它正在foo函数中,将它复制到函数外部(复制构造函数调用),破坏内部函数foo,然后绑定引用.
两个输出都是正确的.RVO是标准明确允许程序的可观察行为发生变化的一个实例.