10

Recently, I want to know how nullptr works. In http://www.stroustrup.com/N1488-nullptr.pdf , I found the code.(Sorry, I don't have 10 reputations, so I can't post images here, you can follow the link above , the code is at page 3.)

The code is cool. And I searched the keyword nullptr in Woboq again, I found the source code in LLVM is different from the above, I copy them below.

struct _LIBCPP_TEMPLATE_VIS nullptr_t
{
    void* __lx;
    struct __nat {int __for_bool_;};
    _LIBCPP_ALWAYS_INLINE _LIBCPP_CONSTEXPR nullptr_t() : __lx(0) {}
    _LIBCPP_ALWAYS_INLINE _LIBCPP_CONSTEXPR nullptr_t(int __nat::*) : __lx(0) {}
    _LIBCPP_ALWAYS_INLINE _LIBCPP_CONSTEXPR operator int __nat::*() const {return 0;}
    template <class _Tp>
        _LIBCPP_ALWAYS_INLINE _LIBCPP_CONSTEXPR
        operator _Tp* () const {return 0;}
    template <class _Tp, class _Up>
        _LIBCPP_ALWAYS_INLINE
        operator _Tp _Up::* () const {return 0;}
    friend _LIBCPP_ALWAYS_INLINE _LIBCPP_CONSTEXPR bool operator==(nullptr_t, nullptr_t) {return true;}
    friend _LIBCPP_ALWAYS_INLINE _LIBCPP_CONSTEXPR bool operator!=(nullptr_t, nullptr_t) {return false;}
};
inline _LIBCPP_ALWAYS_INLINE _LIBCPP_CONSTEXPR nullptr_t __get_nullptr_t() {return nullptr_t(0);}
#define nullptr _VSTD::__get_nullptr_t()

The most diference is, it defines struct __nat and two functions

_LIBCPP_ALWAYS_INLINE _LIBCPP_CONSTEXPR nullptr_t(int __nat::*) : __lx(0) {}
_LIBCPP_ALWAYS_INLINE _LIBCPP_CONSTEXPR operator int __nat::*() const {return 0;}

I thought it for a long time, and I still don't understand why LLVM implemented it like this. Can someone give me any advice?

compor
  • 2,239
  • 1
  • 19
  • 29
  • 5
    Don't sorry. You shouldn't post code as image. –  Aug 29 '18 at 07:40
  • 1
    The important part is that this code is used only when `#ifdef _LIBCPP_HAS_NO_NULLPTR` (some sort of compatibility mode perhaps?), otherwise it is just `typedef decltype(nullptr) nullptr_t;` – user7860670 Aug 29 '18 at 07:55
  • They have `__nat` at other places as well: https://stackoverflow.com/questions/50695153/nat-class-in-clang-standard-libarry – geza Aug 29 '18 at 07:56
  • 1
    Maybe this has to do something with the safe bool idiom. – geza Aug 29 '18 at 08:07

0 Answers0