我刚刚读到了RVO (返回值优化)和NRVO (名为返回值优化)。下面是两个例子
//Example of RVO
Bar Foo()
{
return Bar();
}
//Example of NVRO
Bar Foo()
{
Bar bar;
return bar;
}这是合理的,一个很好的编译器优化。但是,我从Stanley的"C++引物“中读到,”永远不要返回指向Local的引用或指针“(CH6.3.2),示例代码是
//disaster: this function returns a reference to a local object
const string &manip()
{
string ret;
// transform ret in some way
if (!ret.empty())
return ret; // WRONG: returning a reference to a local object!
else
return "Empty"; // WRONG: "Empty" is a local temporary string
}我不明白,这个例子和RVO的例子有什么不同吗?如果它们是相同的,我如何确保编译器将进行RVO优化,而不是由于调用堆栈展开而导致未定义的行为?
发布于 2014-12-31 07:41:21
它们是不同的。
Bar Foo();按值返回,则复制本地对象。
const string &manip();通过引用返回,将返回本地对象本身,而引用在函数返回的同时无效。
https://stackoverflow.com/questions/27717786
复制相似问题