是否舍弃* this的const会导致不确定的行为? [英] Does cast away const of *this cause undefined behavior?

查看:84
本文介绍了是否舍弃* this的const会导致不确定的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码进行编译。

但是它会引起任何未定义的行为吗?

But would it cause any undefined behavior?

我想丢弃const * this

I want to cast away the const of *this.

这是为了允许 const my_iterator 对其指向的数据进行变异。

This is for allowing a const my_iterator to mutate the data it points at.

测试:

class A {
public:
    A(const int x) : x_(x) {}
    void set_x(int x) { x_ = x; }
    void set_x2(const int x) const {
        const_cast<A&>(*this).set_x(x);
    }
    int x_;
};

int main() {
    A a(10);
    a.set_x2(100);
}


推荐答案

您的示例不是未定义的行为因为 a 不是 const 。但是,如果 a const ,则将是:

Your example is not undefined behavior because a is not const. However, if a were const, it would be:

int main() {
    const A a(10);
    a.set_x2(100);
}

这篇关于是否舍弃* this的const会导致不确定的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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