c++ - 合格的 id,它们是左值还是纯右值?

标签 c++ c++11 language-lawyer lvalue qualified-name

我试图在 C++11 标准的第 §5.1.1/8 段(第 87 页)中验证此声明(我强调的)

A nested-name-specifier that denotes a class, optionally followed by the keyword template (14.2), and then followed by the name of a member of either that class (9.2) or one of its base classes (Clause 10), is a qualified-id; 3.4.3.1 describes name lookup for class members that appear in qualified-ids. The result is the member. The type of the result is the type of the member. The result is an lvalue if the member is a static member function or a data member and a prvalue otherwise.

使用以下代码段:

#include <iostream>

namespace N {
    class A {
    public:
        int i;
        void f();
    };
}

int main()
{
    std::cout << &N::A::f << '\n';
    std::cout << &N::A::i << '\n';
}

clanggcc 编译此代码,VS2013 需要成员函数 f 的定义。

三个都打印

1
1

但我不知道这些数字是从哪里来的。

live example

根据上面突出显示的段落,表达式 N::A::f 是纯右值,因为 f 不是静态成员函数。尽管如此,我还是能够在代码中获取它的地址。

同时,在 §5.3.1/3 中读到(强调我的):

The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. If the operand is a qualified-id naming a non-static member m of some class C with type T, the result has type “pointer to member of class C of type T” and is a prvalue designating C::m.

这给人的印象是 N::A::fN::A::i 都不是左值,因为它们是 qualified-id s.

最佳答案

but I have no idea where these numbers come from.

指向成员的指针不是指针。没有 operator<<可以输出它们的原始值,最好的 也是唯一的 匹配是输出 bool 的那个值。因此它们被转换为 bool (这显然会产生 true )并且输出是 1 .尝试插入 std::boolalpha并再次检查输出。

Nonetheless, I was able to take its address in the code.

这让您感到惊讶吗?您引用了允许并解释这个确切构造的部分。它明确指出,采用命名非静态成员的限定 ID 的地址指定该成员。

qualified-id 不仅是左值或右值。这完全取决于上下文。如果他们从该成员类或其任何子类外部指定非静态成员,则它们必须是纯右值,因为它们不指定任何特定对象而是指定值(或信息,换句话说 - 类型和偏移量).

关于c++ - 合格的 id,它们是左值还是纯右值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26346386/

相关文章:

c++ - OpenGL 链式平移/旋转

c++ - 是否将指向第一个成员的指针解释为类本身定义良好?

c++ - BGL - BFS/DFS 访问者,访问顶点颜色

c++ - 哪个编译器(如果有的话)在参数包扩展中有错误?

c - 为什么此代码打印 1 2 2 而不是预期的 3 3 1?

c++ - 有条件地添加到重载集是否合法

c++ - 喜欢 atoi 但要漂浮

C++ 帮助连接 TCHAR

c++ - 可以将不同的 GCC 方言联系在一起吗?

sockets - boost async_accept无法与boost asio use_future选项一起使用