const_cast std :: vector [英] const_cast std::vector
问题描述
我有一个向量类型 const std :: vector< const Array *> & objects
,作为参数传递给方法。
I have a vector with type const std::vector<const Array*> &objects
which is passed as an argument to the method.
我想要const_cast,但是我不能做某些原因。我试过:
I want to const_cast but I can't do it for some reason. I have tried:
vector< const Array *> obj = const_cast< const std :: vector< const Array *> >(objects);
和其他一些方法,但它不断抱怨。
and some other ways but it keeps complaining.
任何想法?
推荐答案
t 。更改函数的签名以接受非const引用,您可以通过执行以下操作来风险UB:
Firstly, don't. Change your function's signature to take a non-const reference, you risk UB by doing this:
const std::vector<const Array*> myData = /* fill */;
yourFunction(myData); // try to modify my stuff and you get UB!
现在如果你仍然相信,无论什么原因(如传统的API),都是这样做的:
Now if you are still convinced you have to, for whatever reason (like legacy API), it's done like this:
vector<const Array*>& obj = const_cast<std::vector<const Array*>&>(objects);
现在 obj
和 objects
是指同一个对象,但 obj
不是const限定的。在这一点上,一切都是明确的;它只修改一个const对象是UB,所以要小心。
Now obj
and objects
refer to the same object, but obj
is not const-qualified. At this point, everything is well-defined; it's only modifying a const object that is UB, so be careful.
这篇关于const_cast std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!