猿问

使用nullptr有什么优势?

这段代码在概念上对三个指针(安全指针初始化)执行相同的操作:


int* p1 = nullptr;

int* p2 = NULL;

int* p3 = 0;

那么,分配指针nullptr比给它们分配值NULLor有0什么好处?


慕田峪4524236
浏览 447回答 3
3回答

汪汪一只猫

在该代码中,似乎没有优势。但是请考虑以下重载函数:void f(char const *ptr);void f(int v);f(NULL);&nbsp; //which function will be called?将调用哪个函数?当然,这里的意图是打电话f(char const *),但实际上f(int)会打电话!那是个大问题1,不是吗?因此,解决此类问题的方法是使用nullptr:f(nullptr); //first function is called当然,这并不是的唯一优势nullptr。这是另一个:template<typename T, T *ptr>struct something{};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//primary templatetemplate<>struct something<nullptr_t, nullptr>{};&nbsp; //partial specialization for nullptr由于在模板中,的类型nullptr推导为nullptr_t,因此您可以这样编写:template<typename T>void f(T *ptr);&nbsp; &nbsp;//function to handle non-nullptr argumentvoid f(nullptr_t); //an overload to handle nullptr argument!!!1.在C ++中,NULL定义为#define NULL 0,所以基本上是int,这就是为什么f(int)要调用它。

波斯汪

这里的真正动机是完美的转发。考虑:void f(int* p);template<typename T> void forward(T&& t) {&nbsp; &nbsp; f(std::forward<T>(t));}int main() {&nbsp; &nbsp; forward(0); // FAIL}简而言之,0是一个特殊值,但是值不能通过仅系统类型传播。转发功能是必不可少的,0不能处理它们。因此,绝对有必要引入nullptr,其中类型是特殊的,并且类型确实可以传播。实际上,MSVC团队nullptr在实施右值引用之后必须提前引入,然后自己发现此陷阱。还有一些其他情况nullptr可以使生活更轻松-但这不是核心问题,因为演员可以解决这些问题。考虑void f(int);void f(int*);int main() { f(0); f(nullptr); }调用两个单独的重载。另外,考虑void f(int*);void f(long*);int main() { f(0); }这是模棱两可的。但是,使用nullptr,您可以提供void f(std::nullptr_t)int main() { f(nullptr); }
随时随地看视频慕课网APP
我要回答