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_ptr和std::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)