为什么我可以将0转换为std :: shared_ptr <T>而不是1?

cha*_*ink 3 c++ pointers shared-ptr nullptr c++11

#include <memory>

void f1(std::shared_ptr<bool> ptr) {}

int main() {
    f1(0); // OK
    f1(1); // compilation error: could not convert ‘1’ from ‘int’ to ‘std::shared_ptr<bool>’
}
Run Code Online (Sandbox Code Playgroud)

既为int,为什么01可以转换为std::shared_ptr<T>

如何从转换的残疾1std::shared_ptr<T>编译时进行检查?

如何从转换的残疾1std::nullptr_t编译时进行检查?

R S*_*ahu 7

0是C/C++中的特殊值.许多事情都有效,0但没有1.原因是语言的转换规则.

f1(0); // OK
Run Code Online (Sandbox Code Playgroud)

由于以下转换,这没关系.

0  -> nullptr
nullptr -> std::shared_ptr<bool> // Through a constructor
Run Code Online (Sandbox Code Playgroud)

然而,

f1(1);
Run Code Online (Sandbox Code Playgroud)

因为没有转换可用于转换1为a,所以不行shared_ptr<bool>.

  • @chaosink,文字"0"在语言中是特殊的.编译器必须知道如何以不同方式处理文字"0"和"1".请注意,如果你使用`int i = 0; f1(i);`使用`f1(1);`时会得到类似的错误信息. (3认同)
  • @chaosink它实际上有点糟糕,它不仅仅是文字整数,而是一般的常量积分表达式.编译器必须将`!!!!!!!!! 1'识别为有效的空指针值,因此(1)可分配给指针类型的任何左值,(2)可转换为`std :: nullptr_t`. (2认同)

Mat*_*lia 7

std::shared_ptr<T>有一个构造函数std::nullptr_t,它有一个隐式转换,来自任何有效的空指针常量,包括一个普通的0文字.另一方面,1它不是任何shared_ptr构造函数的有效参数.