通过const&写给班级成员 [英] Writing to class member through const &

查看:80
本文介绍了通过const&写给班级成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中,c样式是否强制转换为 int& ,然后进行分配以对类型为 A的接口进行黑客入侵未定义行为?

In this example, is the c-style cast to int& followed by an assignment to kind of hack the interface of class A undefined behavior?

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

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

If so, what part of the standard can i refer to? Also, is there any reason why this compiles without warnings? (i tested with c++14 on cpp.sh with -Wall, -Wextra and -Wpedantic)

推荐答案

const int& getX() { return x; }

由于此方法未标记为const,因此x是可变int。将引用并转换为const int& amp;。在返回点。请注意,尽管引用是const int,但实际的引用int是可变的。这很重要。

Since this method is not marked const, x is a mutable int. A reference is taken and cast to a const int& at the point of return. Note that although the reference is to a const int, the actual referee int is mutable. This is important.

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

此行采用返回的const int引用和 const_cast 将其引用为int引用。这在c ++中是合法的,句号是句号。 [expr.const.cast]

This line takes the returned const int reference and const_cast's it to an int reference. This is legal in c++, full stop. [expr.const.cast]

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

However, writing through this reference is only legal if the original object being referenced is mutable.

在这种情况下就是这样。

In this case, it is.

您将在 [dcl.type.cv]中找到详细信息

这篇关于通过const&amp;写给班级成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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