最近,我想知道nullptr
是如何工作的。在http://www.stroustrup.com/N1488-nullptr.pdf中,我找到了代码。(对不起,我没有10个好名声,所以我不能在这里发布图片,你可以点击上面的链接,代码在第3页)。
代码很酷。并且我在Woboq中再次搜索关键字nullptr
,我发现LLVM中的源代码与上面的不同,我将它们复制到下面。
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()
最不同的是,它定义了struct __nat
和两个函数
_LIBCPP_ALWAYS_INLINE _LIBCPP_CONSTEXPR nullptr_t(int __nat::*) : __lx(0) {}
_LIBCPP_ALWAYS_INLINE _LIBCPP_CONSTEXPR operator int __nat::*() const {return 0;}
我想了很长一段时间,我仍然不明白为什么LLVM这样实现它。有人能给我一些建议吗?
发布于 2018-12-06 20:12:50
'nullptr_t‘和'nullptr’是不同的东西。
‘'nullptr’只是一个'size_t‘值--在所有平台上都可能是0。
'nullptr_t‘是一种类型,它允许你的代码进行静态检查,并区分重载,比如:
void f(int* pi)
{
std::cout << "Pointer to integer overload\n";
}
void f(double* pd)
{
std::cout << "Pointer to double overload\n";
}
void f(std::nullptr_t nullp)
{
std::cout << "null pointer overload\n";
}
如果你调用'f(nullptr)‘,如果没有定义最后一个重载,会调用哪个重载?
当然,您可以只调用'f((int*)nullptr)‘或'f((double*)nullptr)'...
https://stackoverflow.com/questions/52071913
复制