初始化unique_ptr有什么问题? [英] What's wrong with this initialization of unique_ptr?

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

问题描述

有人可以告诉我,下面的unique_ptr初始化有什么问题吗?

Can somebody tell me, what is wrong with the following initialization of unique_ptr?

int main()
{
  unique_ptr<int> py(nullptr);
  py = new int;
  ....
}

g ++ -O2 xxx.cc -lm -o xxx -std = c ++ 11说:

g++ -O2 xxx.cc -lm -o xxx -std=c++11 says:

error: no match for ‘operator=’ (operand types are    ‘std::unique_ptr<int>’ and ‘int*’)
   py = new int;
      ^

unique_ptr<int> px(new int);

工作正常.

推荐答案

在两段代码中初始化都很好,unique_ptr具有

The initialization is fine in both pieces of code, unique_ptr has constructors for both nullptr and naked pointers.

第一个代码段中失败的是分配,这是因为unique_ptr没有

What is failing in the first snippet is the assignment, that is because unique_ptr does not have an operator= overload that accepts a naked pointer as its right hand side. It does accept another unique_ptr though, so you could do this:

py = unique_ptr<int>{new int};
py = std::make_unique<int>(); // Since c++14

或者您可以查看 reset ,它也可以接受裸露的指针并具有更多内容或更少的意思:

Or you could look at reset that also accepts a naked pointer and has more or less the same meaning:

py.reset(new int);

这篇关于初始化unique_ptr有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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