C++ 为什么我们不能使用=&引用;要共享\u ptr还是唯一\u ptr?

C++ 为什么我们不能使用=&引用;要共享\u ptr还是唯一\u ptr?,c++,c++11,initialization,shared-ptr,unique-ptr,C++,C++11,Initialization,Shared Ptr,Unique Ptr,我发现语法有编译错误 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 std::shared_ptr p=newint(5); 31 41 E:\temprory(如果您愿意,请删除

我发现语法有编译错误

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
std::shared_ptr p=newint(5);
31 41 E:\temprory(如果您愿意,请删除它)\1208.cpp[Error]请求从“int*”转换为非标量类型“std::shared\u ptr”
但是没关系

std::shared_ptr<int> p(new int(5));
std::shared_ptr p(新int(5));
unique_ptr
相同

但是我不知道为什么它是被禁止的。

原始指针的构造函数是显式的<代码>标准::共享p=新整数(5)是,它不考虑<代码>显式< /代码>构造函数。

复制初始化的权限小于直接初始化:显式构造函数不转换构造函数,也不考虑复制初始化

对于,
explicit
构造函数被考虑,然后
std::shared_ptr p(新的int(5))工作正常

为什么构造函数是显式的? 防止无意的隐式转换和所有权转移。e、 g

void foo(std::unique_ptr<int> p) { ... }

想象一下,如果您意外地传递了一个
int*
指针,该指针指向一个接受
std::shared\u ptr
的函数。函数完成后,指针将被释放。如果你真的想转让所有权,您应该明确指出。

C++不允许从原始指针复制初始化
共享的\u ptr
,因为
共享的\u ptr
很容易以从任意原始指针意外隐式转换为实际上不管理它的
共享的\u ptr
而告终。

构造函数是标记为显式
,因此您不能复制初始值我相信OP询问的是使此构造函数显式的决策原理。
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