【发布时间】:2013-07-03 02:13:20
【问题描述】:
在comment to another questionJonathan Wakely 回复我的声明:
对于局部变量函数返回,您永远不需要显式移动 价值。这是隐含的移动
->
...永远不要说永远...如果局部变量,您需要显式移动 与返回类型不同,例如
std::unique_ptr<base> f() { auto p = std::make_unique<derived>(); p->foo(); return p; },但是 如果类型相同,它会尽可能移动......
所以有时我们可能不得不在返回时移动一个局部变量。
例子
std::unique_ptr<base> f() {
auto p = std::make_unique<derived>();
p->foo();
return p;
}
很好,因为它提供了compilation error
> prog.cpp:10:14: error: cannot convert ‘p’ from type
> ‘std::unique_ptr<derived>’ to type ‘std::unique_ptr<derived>&&’
但我想知道一般情况下是否有很好的机会检测到这一点 - 这是语言规则或unique_ptr的限制吗??
【问题讨论】:
标签: c++ c++11 return implicit-conversion move-semantics