gpt4 book ai didi

c++ - 丢弃 const of *this 会导致未定义的行为吗?

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:11 27 4
gpt4 key购买 nike

下面的代码编译。它似乎运行良好。

但是它会导致任何未定义的行为吗?

我想抛弃 *this 的常量。

这是为了允许 const my_iterator 改变它指向的数据。

测试:

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。但是,如果 aconst,它将是:

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

关于c++ - 丢弃 const of *this 会导致未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50163959/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com