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

五迷三道 提交于 2019-12-04 07:11:22

问题


Actually I am writing my own version of all library classes, and I don't want to include the STL files into my class file. So, for example, I want to check whether the node is equal to null. If I write something like

#define nullptr 0

Then it is not working with some other node pointer (i.e. Node *root = nullptr)


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/44517556/how-to-define-our-own-nullptr-in-c98

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