What are the uses of the type `std::nullptr_t`?

有些话、适合烂在心里 提交于 2019-12-17 20:03:52

问题


I learned that nullptr, in addition to being convertible to any pointer type (but not to any integral type) also has its own type std::nullptr_t. So it is possible to have a method overload that accepts std::nullptr_t.

Exactly why is such an overload required?


回答1:


If more than one overload accepts a pointer type, an overload for std::nullptr_t is necessary to accept a nullptr argument. Without the std::nullptr_t overload, it would be ambiguous which pointer overload should be selected when passed nullptr.

Example:

void f(int *intp)
{
    // Passed an int pointer
}

void f(char *charp)
{
    // Passed a char pointer
}

void f(std::nullptr_t nullp)
{
    // Passed a null pointer
}



回答2:


There are some special cases that comparison with a nullptr_t type is useful to indicate whether an object is valid.

For example, the operator== and operator!= overloads of std::function could only take nullptr_t as the parameter to tell if the function object is empty. For more details you could read this question.




回答3:


Also, what other type would you give it, that doesn't simply re-introduce the problems we had with NULL? The whole point is to get rid of the nasty implicit conversions, but we can't actually change behaviour of old programs so here we are.



来源:https://stackoverflow.com/questions/12066721/what-are-the-uses-of-the-type-stdnullptr-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!