1

I know this kind of questions aren't really welcome here but I must ask: why don't unique_ptr/shared_ptr/etc have an operator= overload for type T?

It would seem more natural to write

std::unique_ptr<int> p = new int(5);

instead of

std::unique_ptr<int> p(new int(5));

or any other more verbose method.

4

2 回答 2

6

如果你被允许写这个:

std::unique_ptr<int> p = new int(5);

然后你也可以写这些:

void Func1(std::unique_ptr<int> p);

Func1(new int(5));

std::unique_ptr<int> Func2() {return new int(5);}

或者更危险的:

void Func1(std::unique_ptr<int> p);

int *pInt = new int(5);
Func1(pInt); //You no longer own the pointer anymore.
delete pInt; //You're now deleting a pointer you don't own.

由于显而易见的原因,这是不可接受的。他们不希望从裸指针隐式转换为唯一指针;如果您想创建一个unique_ptr,您必须明确说明:Func1(std::unique_ptr<int>(pInt));现在,每个人都可以看到您正在将所有权从您自己转移到该函数。

此外,它operator=不会使这个工作。它的explicit单参数构造函数unique_ptr阻止了复制初始化语法的工作。

于 2013-02-17T01:07:50.643 回答
2

What you're referring to is the fact that the constructor of unique_ptr<T> that takes a raw T pointer is explicit. This is deliberate. A unique pointer takes ownership, and that should not happen implicitly. The user should always know explicitly when ownership is created, transferred and ended.

In a more draconian world one could imagine a unique_ptr that doesn't take any raw pointers at all, and instead only allows direct creation of the owned object:

auto p = std::unique_ptr<T>::make(arg1, arg2, arg3);
                             // Calls "new T(arg1, arg2, arg3)".
                             // Not real code.
于 2013-02-17T01:18:18.557 回答