为什么不能使用nullptr的地址? [英] Why can't you take the address of nullptr?

查看:316
本文介绍了为什么不能使用nullptr的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11标准中,我不明白为什么不允许使用nullptr的地址,而允许 接受其自己的std :: nullptr_t实例的地址的原因.除了nullptr是保留关键字这一事实之外,是否有任何指定的理由来做出此决定?

In the C++11 standard, I don't understand the reason why taking the address of nullptr is disallowed whereas one is allowed to take the address of their own std::nullptr_t instances. Aside from the fact that nullptr is a reserved keyword, is there any designated reasoning for this decision?

仅仅因为它使我感到有趣,所以我尝试使用以下功能来规避此限制:

Simply because it amuses me, I attempted to circumnavigate this restriction with the following function:

decltype(nullptr)* func(const decltype(nullptr) &nref) noexcept
{
    return const_cast<decltype(nullptr)*>(reinterpret_cast<const decltype(nullptr)*>(&nref));
}

我必须在参数上使用reinterpret_cast,因为没有它,我会收到歇斯底里的错误:

I had to use reinterpret_cast on the parameter because without it I was getting the hysterical error:

error: invalid conversion from 'std::nullptr_t*' to 'std::nullptr_t*' [-fpermissive]

当我通过直接传递 nullptr 调用此函数时,每次都会得到一个不同的地址.是否为nullptr实时动态分配了一个用于比较等的地址?或者(可能更有可能)编译器是否强制底层对象的临时副本?

When I call this function by passing nullptr directly I get a different address each time. Is nullptr dynamically assigned an address just-in-time for comparisons and such? Or (probably more likely) perhaps is the compiler forcing a temporary copy of the underlying object?

当然,这些都不是至关重要的信息,我只是发现有趣的是为什么实施了此特定限制(以及随后为什么看到自己的行为).

Of course none of this is vital information, I just find it interesting why this particular restriction was implemented (and subsequently why I am seeing the behavior I am).

推荐答案

这与无法获取5的地址相同,即使您在给int赋予了值<之后也可以获取其地址5.没关系,nullptr_t没有其他价值.

It's the same as not being able to take the address of 5 even though you can take the address of an int after giving it the value 5. It doesn't matter that there's no alternative value for a nullptr_t to have.

值没有地址;对象.

当您将这样的值传递给const &参数或将值绑定到const引用时(例如通过static_cast< T const & >( … )或声明命名引用T const & foo = …;),将生成一个临时对象.您看到的地址是临时地址.

A temporary object is generated when you pass such a value to a const & parameter, or otherwise bind a value to a const reference, such as by static_cast< T const & >( … ) or declaring a named reference T const & foo = …;. The address you're seeing is that of the temporary.

这篇关于为什么不能使用nullptr的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆