How to define our own nullptr in c++98?

假装没事ソ 提交于 2019-12-02 13:36:31

How to do that is mentioned in the book: Effective C++, 2nd edition by Scott Meyers (newer edition is available) in chapter: "Item 25: Avoid overloading on a pointer and a numerical type.".

It is needed if your compiler doesn't know the nullptr keyword introduced by C++11.

const                         /* this is a const object...     */
class nullptr_t
{
public:
   template<class T>          /* convertible to any type       */
   operator T*() const        /* of null non-member            */
      { return 0; }           /* pointer...                    */

   template<class C, class T> /* or any type of null           */
      operator T C::*() const /* member pointer...             */
      { return 0; }   

private:
   void operator&() const;    /* Can't take address of nullptr */

} nullptr = {};               /* and whose name is nullptr     */

That book is definitely worth reading.


The advantage of nullptr over NULL is, that nullptr acts like a real pointer type thus it adds type safety whereas NULL acts like an integer just set to 0 in pre C++11.

You should not define macros with identifiers that are keywords.

Even if you don't use STL, there is no need to define your own nullptr, because it is not part of STL (nor the standard library), but is part of the (C++) language itself.

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