C++ 中 const 到非 const 的转换 [英] const to Non-const Conversion in C++

查看:99
本文介绍了C++ 中 const 到非 const 的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些天我对 const 关键字真的很恼火,因为我不太熟悉它.我有一个存储所有 const 指针的向量,例如 vector<const BoxT<T>*>*Q_exclude,并且在另一个类的构造函数中,我需要这个队列中的一个元素作为参数传入,并将它分配给一个非常量成员.我的问题是:

I'm really annoyed by const keyword these days, as I'm not quite familiar with it. I had a vector that stores all const pointers like vector<const BoxT<T> *> *Q_exclude, and in the constructor of another class, I need an element in this queue to be passed in as a parameter and assign it to a non-const member. My question is:

如何将 const 变量分配给非 const 变量?我知道这没有意义,因为毕竟 const 是 const,不应该以任何方式改变.但是那个烦人的成员变量真的必须在这个过程中改变!我也可能将向量中的数据类型更改为非常量,但这会做太多工作.或者有谁知道如何避免这种情况?

How do I assign a const variable to a non-const variable? I know this doesn't make sense because after all, a const is a const, and should not be changed by any mean. But that annoying member variable REALLY has to be changed during the process! I might also change the data type in the vector to be non-const, but that would be too much work. Or does anyone know how to avoid such situation?

推荐答案

您可以将 const 对象分配给非 const 对象就好了.因为您是在复制并因此创建了一个新对象,所以不会违反 constness.

You can assign a const object to a non-const object just fine. Because you're copying and thus creating a new object, constness is not violated.

像这样:

int main() {
   const int a = 3;
   int b = a;
}

不同如果你想获得一个指针或引用原件,const 对象:

It's different if you want to obtain a pointer or reference to the original, const object:

int main() {
   const int a = 3;
   int& b = a;       // or int* b = &a;
}

//  error: invalid initialization of reference of type 'int&' from
//         expression of type 'const int'

如果你真的必须的话,你可以使用 const_cast 来绕过类型安全,但请记住你正在这样做:摆脱类型安全.仍然未定义通过 b 修改 a>下面的例子:

You can use const_cast to hack around the type safety if you really must, but recall that you're doing exactly that: getting rid of the type safety. It's still undefined to modify a through b in the below example:

int main() {
   const int a = 3;
   int& b = const_cast<int&>(a);

   b = 3;
}

虽然它编译时没有错误,但任何事情都可能发生,包括打开黑洞或将您辛苦赚来的所有积蓄转入我的银行账户.

Although it compiles without errors, anything can happen including opening a black hole or transferring all your hard-earned savings into my bank account.

如果你已经达到了你认为这样做的必要条件,我会紧急重新审视你的设计,因为它有很大的问题.

If you have arrived at what you think is a requirement to do this, I'd urgently revisit your design because something is very wrong with it.

这篇关于C++ 中 const 到非 const 的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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