#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>’
}
都是int
,为什么0
却可以1
转换成std::shared_ptr<T>
?
在编译时如何检查从1
到std::shared_ptr<T>
的转换障碍?
在编译时如何检查从1
到std::nullptr_t
的转换障碍?
答案 0 :(得分:7)
0
是C / C ++中的特殊值。 0
有很多功能,但1
却没有。原因是语言的转换规则。
f1(0); // OK
没关系,因为进行了以下转换。
0 -> nullptr
nullptr -> std::shared_ptr<bool> // Through a constructor
但是,
f1(1);
不能正常运行,因为没有可用的转换将1
转换为shared_ptr<bool>
。
答案 1 :(得分:7)
std::shared_ptr<T>
具有一个使用std::nullptr_t
的构造函数,对于该构造函数,存在任何有效的空指针常量的隐式转换,该常量包含一个普通的0
文字。另一方面,对于任何1
构造函数,shared_ptr
都不是有效的参数。
答案 2 :(得分:0)
除了其他答案外,一种解决方法是改用std::make_shared宏:
f1(std::make_shared<bool>(0)); // OK
f1(std::make_shared<bool>(1)); // OK
这样,您将能够向函数提供任何整数文字。简单的工作示例:
#include <iostream>
#include <memory>
void f1(std::shared_ptr<bool> ptr) {
std::cout << std::boolalpha << *ptr << '\n';
}
int main() {
f1(std::make_shared<bool>(0)); // OK
f1(std::make_shared<bool>(1)); // OK
f1(std::make_shared<bool>(2)); // OK
}