Why can't nullptr convert to int?

后端 未结 4 2122
不知归路
不知归路 2021-02-07 09:32

Summary: nullptr converts to bool, and bool converts to int, so why doesn\'t nullptr convert to int

4条回答
  •  伪装坚强ぢ
    2021-02-07 09:49

    Because it is exactly the main idea of nullptr.

    nullptr was meant to avoid this behavior:

    struct myclass {};
    
    void f(myclass* a) { std::cout << "myclass\n"; }
    void f(int a) { std::cout << "int\n"; }
    
    // ...
    
    f(NULL); // calls void f(int)
    

    If nullptr were convertible to int this behavior would occur.

    So the question is "why is it convertible to bool?".

    Syntax-"suggarness":

    int* a = nullptr;
    if (a) {
    }
    

    Which looks way better than:

    if (a == nullptr) {
    }
    

提交回复
热议问题