【发布时间】:2014-11-11 03:57:19
【问题描述】:
std::unique_ptr<int> ptr() {
std::unique_ptr<int> p(new int(3));
return p; // Why doesn't this require explicit move using std::move?
} // Why didn't the data pointed to by 'p' is not destroyed here though p is not moved?
int main() {
std::unique_ptr<int> a = ptr(); // Why doesn't this require std::move?
std::cout << *a; // Prints 3.
}
在上面的代码中,函数ptr()返回一个p的副本。当p 超出范围时,应该删除数据“3”。但是代码如何在没有任何访问冲突的情况下工作?
【问题讨论】:
-
它实际上使用了
std::unique_ptr<>的move constructor。 -
请参阅this related question。无论谁把它作为“未定义行为”的欺骗而结束,都需要喝杯咖啡。
-
@MattMcNabb 仍然必须有一个可行的复制/移动复制构造函数重载。
标签: c++ c++11 move-semantics copy-elision