通过const&写入类成员

Mar*_*n G 2 c++ const const-cast undefined-behavior

在这个例子中,是c样式的强制转换,int&然后是一个hack类的A未定义行为的接口的赋值?

class A
{
public:
    A()
    : x(0)
    {
    }

    ~A()
    {
        std::cout << x << std::endl;
    }

    const int& getX()
    {
        return x;
    }

private:
    int x;
};

int main()
{
    A a;
    int& x = (int&)a.getX();
    x = 17;
    std::cout << x << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:

17
17
Run Code Online (Sandbox Code Playgroud)

如果是这样,我可以参考标准的哪一部分?此外,有没有任何理由为什么这个编译没有警告?(我在cpp.sh上用c ++ 14测试了-Wall,-Wextra和-Wpedantic)

Ric*_*ges 8

const int& getX() { return x; }
Run Code Online (Sandbox Code Playgroud)

由于此方法未标记为const,因此x是可变int.引用并转换为const int和返回点.请注意,虽然引用是const int,但实际的裁判int是可变的.这个很重要.

int& x = (int&)a.getX();
Run Code Online (Sandbox Code Playgroud)

该行获取返回的const int引用,并将const_cast其作为int引用.这在c ++中是合法的,完全停止.[expr.const.cast]

但是,如果引用的原始对象是可变的,则通过此引用进行写入是合法的.

在这种情况下,它是.

你会在[dcl.type.cv]找到详细信息.