c++ - 抛弃 *this 的 const 会导致未定义的行为吗?
问题描述
以下代码编译。它似乎运行良好。
但它会导致任何未定义的行为吗?
我想抛弃*this
.
这是为了允许 aconst 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
is not const
。但是,如果a
是const
,它将是:
int main() {
const A a(10);
a.set_x2(100);
}
推荐阅读
- angular - 在循环中对同一 API 进行角度多次调用
- python - ADB Python-Daemon 子进程未连接
- c# - 将字节数组解码为 C# 中的对象时出现问题
- r - 散列小标题的每一行
- python - python socket是否基本上像计算机到计算机VPN一样通过互联网连接主机和客户端?
- php - 通过ajax提交表单时出现SQL错误
- html - 基于 CSS 的图像幻灯片不会缩放到移动设备上的高度:100%
- numpy - 重塑一个 numpy 向量
- database - 使用和运行 brew services start mongodb-community@4.2 出现问题
- php - 有没有办法在 Wordpress 注册表单中添加下拉列表?