缺少unique_ptr和friends operator = overload

use*_*963 1 c++ std c++11

我知道这种问题在这里并不受欢迎,但我必须要问:为什么unique_ptr/shared_ptr/etc没有类型为T的operator =重载?

写作似乎更自然

std::unique_ptr<int> p = new int(5);
Run Code Online (Sandbox Code Playgroud)

代替

std::unique_ptr<int> p(new int(5));
Run Code Online (Sandbox Code Playgroud)

或任何其他更冗长的方法.

Nic*_*las 6

如果你被允许写这个:

std::unique_ptr<int> p = new int(5);
Run Code Online (Sandbox Code Playgroud)

然后你也可以写这些:

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

Func1(new int(5));

std::unique_ptr<int> Func2() {return new int(5);}
Run Code Online (Sandbox Code Playgroud)

或者更危险的是:

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.
Run Code Online (Sandbox Code Playgroud)

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

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

  • @ user1233963:然后就没有办法将指针放入`unique_ptr`.我们的目标是确保您不会意外地执行此操作,而不会看到***`unique_ptr`***位于所有权转移所在的站点.由于C++的规则,这也意味着你不能使用复制初始化(又名:`typename var = stuff;`)你必须使用direct initializaton(又名:`typename var(stuff);`). (2认同)