【发布时间】:2013-05-29 11:10:48
【问题描述】:
我试图了解std::unique_ptr 的工作原理,为此我找到了this 文档。作者从下面的例子开始:
#include <utility> //declarations of unique_ptr
using std::unique_ptr;
// default construction
unique_ptr<int> up; //creates an empty object
// initialize with an argument
unique_ptr<int> uptr (new int(3));
double *pd= new double;
unique_ptr<double> uptr2 (pd);
// overloaded * and ->
*uptr2 = 23.5;
unique_ptr<std::string> ups (new std::string("hello"));
int len=ups->size();
让我困惑的是这一行
unique_ptr<int> uptr (new int(3));
我们使用整数作为参数(在圆括号之间)
unique_ptr<double> uptr2 (pd);
我们使用指针作为参数。有什么区别吗?
我还不清楚的是,以这种方式声明的指针与以“正常”方式声明的指针有何不同。
【问题讨论】:
-
new int(3)返回一个指向新int的指针,就像pd是一个指向新double的指针一样。 -
unique_ptr 声明位于
<memory>而不是<utility>
标签: c++ pointers std unique-ptr