如何可以返回一个unique_ptr的值没有std :: move? [英] How can a unique_ptr be returned by value without std::move?

查看:691
本文介绍了如何可以返回一个unique_ptr的值没有std :: move?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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'应该被删除。但是代码如何工作没有任何访问冲突?

In the above code, the function ptr() returns a copy of p. When p goes out of scope, the data '3' should get deleted. But how does the code work without any access violation?

推荐答案

这在C ++ 11标准§12.8 / 32 / p>

This is set out in the C++11 standard, § 12.8/32:


当满足复制操作的限制条件或满足
时,保存源对象为函数参数
和要复制的对象由一个左值指定, overload
分辨率为复制选择构造函数首先执行
,就像对象被指定为rvalue
....

(强调我的)。在纯英语中,这意味着当涉及到重载分辨率时,lvalue p 可以被当作 rvalue 它是复制elision的候选者 。这反过来意味着移动构造函数在重载解析上被拾起(实际上,移动副本可能已经被舍弃了。)

(emphasis mine). In plain english, it means that the lvalue p can be treated as an rvalue when it comes to overload resolution, because it is a candidate for copy elision. This in turn means the move constructor is picked up on overload resolution (in actual fact, the move copy is probably elided anyway.)

这篇关于如何可以返回一个unique_ptr的值没有std :: move?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆