通过 const & 写入 class 成员

Writing to class member through const &

在此示例中,是否将 c 样式强制转换为 int&,然后进行赋值以破解 class 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;
}

输出:

17
17

如果可以,我可以参考标准的哪一部分?另外,有什么理由可以编译而没有警告吗? (我用 c++14 在 cpp.sh 上用 -Wall、-Wextra 和 -Wpedantic 进行了测试)

const int& getX() { return x; }

由于这个方法没有被标记为const,x是一个可变的int。在 return 处引用并转换为 const int&。请注意,尽管引用的是 const int,但实际的 referee int 是可变的。这很重要。

int& x = (int&)a.getX();

此行采用 returned const int 引用并将其 const_cast 转换为 int 引用。这在 C++ 中是合法的,句号。 [expr.const.cast]

但是,仅当被引用的原始对象是可变的时,通过此引用写入才合法。

在这种情况下,它是。

您将在 [dcl.type.cv]

中找到详细信息