为什么我允许复制unique_ptr? [英] Why am I allowed to copy unique_ptr?

查看:146
本文介绍了为什么我允许复制unique_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

从函数返回unique_ptr


20.7.1.2 [unique。

  //禁用左值复制
unique_ptr(const unique_ptr&) =删除;
unique_ptr& operator =(const unique_ptr&)= delete;

那么,为什么下面的代码编译得很好?

  #include< memory> 
#include< iostream>

std :: unique_ptr< int> bar()
{
std :: unique_ptr< int> p(new int(4));
return p;


int main()
{
auto p = bar();

std :: cout<<< p<< std :: endl;
}

我这样编译它:

  g ++ -O3 -Wall -Wextra -pedantic -std = c ++ 0x kel.cpp 

编译器:g ++版本4.6.1 20110908(Red Hat 4.6.1-9)

解决方案在返回语句中,如果返回一个局部变量,则表达式将被视为右值,并自动移动。因此它类似于:

  return std :: move(p); 

它调用 unique_ptr(unique_ptr&& amp;) bar()会产生一个临时值,它是一个右值,并且也适当地转移到 main 中的 p


Possible Duplicate:
Returning unique_ptr from functions

20.7.1.2 [unique.ptr.single] defines copy constructor like this :

// disable copy from lvalue
unique_ptr(const unique_ptr&) = delete;
unique_ptr& operator=(const unique_ptr&) = delete;

So, why the following code compiles fine?

#include <memory>
#include <iostream>

std::unique_ptr< int > bar()
{
  std::unique_ptr< int > p( new int(4));
  return p;
}

int main()
{
  auto p = bar();

  std::cout<<*p<<std::endl;
}

I compiled it like this :

g++ -O3  -Wall -Wextra -pedantic -std=c++0x kel.cpp

The compiler : g++ version 4.6.1 20110908 (Red Hat 4.6.1-9)

解决方案

In the return statement, if you return a local variable, the expression is treated as an rvalue, and thus automatically moved. It is thus similar to:

  return std::move(p);

It invokes the unique_ptr(unique_ptr&&) constructor.

In the main function, bar() produces a temporary, which is an rvalue, and is also properly moved into the p in main.

这篇关于为什么我允许复制unique_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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