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

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

问题描述

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

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 对象就可以了。因为您正在复制并因此创建了一个新对象,所以不会违反 const ness。

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 still 仍未定义/codepad.org/ZGUgLJR1 rel = noreferrer>以下示例:

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.

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

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