Why can I convert 0 to an std::shared_ptr<T> but not 1?

  • A+
Category:Languages
#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>’ } 

Both as int, why 0 but 1 can be converted to std::shared_ptr<T>?

How the disability of conversion from 1 to std::shared_ptr<T> be checked when compiling?

How the disability of conversion from 1 to std::nullptr_t be checked when compiling?

 


0is a special value in C/C++. Many things work with 0 but not with 1. The reason(s) for that are the conversion rules of the language.

f1(0); // OK 

That's ok because of the following conversions.

0  -> nullptr nullptr -> std::shared_ptr<bool> // Through a constructor 

However,

f1(1); 

is not ok since there is no conversion available to convert 1 to a shared_ptr<bool>.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: