为什么我们不能将"="用于shared_ptr或unique_ptr?

cha*_* jc 4 c++ initialization shared-ptr unique-ptr c++11

我知道语法得到编译错误.

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

31 41 E:\temprory (delete it if u like)\1208.cpp [Error] conversion from 'int*' to non-scalar type 'std::shared_ptr<int>' requested
Run Code Online (Sandbox Code Playgroud)

但没关系

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

同样的unique_ptr;

但我不知道为什么禁止它.

son*_*yao 12

构造std::shared_ptrstd::unique_ptr获取原始指针是explicit; std::shared_ptr<int> p = new int(5);复制初始化,它不考虑explicit构造函数.

复制初始化比直接初始化更不容许:显式构造函数不转换构造函数,也不考虑复制初始化.

对于直接初始化,explicit构造函数被认为是std::shared_ptr<int> p(new int(5));正常工作.

为什么构造函数是explicit

防止无意的隐式转换和所有权转移.例如

void foo(std::unique_ptr<int> p) { ... }
Run Code Online (Sandbox Code Playgroud)

然后

int* pi = new int(5);
foo(pi); // if implicit conversion is allowed, the ownership will be transfered to the parameter p
// then when get out of foo pi is destroyed, and can't be used again
Run Code Online (Sandbox Code Playgroud)


msc*_*msc 5

C++不允许shared_ptr从原始指针复制初始化a ,因为shared_ptr太容易导致从一些任意原始指针到shared_ptr实际上没有管理它的意外隐式转换.