What exactly is nullptr?

前端 未结 14 2683
无人及你
无人及你 2020-11-22 01:12

We now have C++11 with many new features. An interesting and confusing one (at least for me) is the new nullptr.

Well, no need anymore for the nasty mac

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 01:25

    Let's say that you have a function (f) which is overloaded to take both int and char*. Before C++ 11, If you wanted to call it with a null pointer, and you used NULL (i.e. the value 0), then you would call the one overloaded for int:

    void f(int);
    void f(char*);
    
    void g() 
    {
      f(0); // Calls f(int).
      f(NULL); // Equals to f(0). Calls f(int).
    }
    

    This is probably not what you wanted. C++11 solves this with nullptr; Now you can write the following:

    void g()
    {
      f(nullptr); //calls f(char*)
    }
    

提交回复
热议问题