我有一个名为foo的函数:
std::vector<T> foo() {
std::vector<T> result;
// populate result
{
/*
for loop with result.push_back().
ignore real code.
*/
}
//
return result; <-- note there without std::move
}
如果我按照以下方式分配,它会做多余的复制吗?
const auto v = foo(); <-- will it move the vector by default?
const auto &v = foo(); <-- same question as above, assuming T is movable
我特别关注第二种情况,对于第一种情况,编译器很可能知道要将foo()的结果移动到v中。
const auto &v = foo();
对于这种情况,foo()函数创建了一个临时的result。由于v是一个引用,所以它无法将result移动到v上。因此需要创建一个新的副本。我的理解正确吗?
result
和v
的地址来检查它们是否指向同一位置。据我所见(http://coliru.stacked-crooked.com/a/008e806a76afed61),它们打印的是相同的地址。因此,一个很好的猜测是,没有进行复制。 - badolaconst &
允许绑定到临时对象。 - badola