const_cast std::vector

依然范特西╮ 提交于 2019-12-11 03:35:44

问题


I have a vector with type const std::vector<const Array*> &objects which is passed as an argument to the method.

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.

Any ideas ?


回答1:


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!

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);

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.




回答2:


I need to pass it to a function which needs to iterate over it (it doesnt to any modification)

Use a const_iterator.

You want to cast a const std::vector<const Array*> to a const std::vector<const Array*>? Aren't they identical. If you want to remove the const:

std::vector<const Array*> obj = const_cast<std::vector<const Array*> >(objects);
//                                         |
//                                      no const

But a more important question would be: why? If objects is const, you're not supposed to modify it.




回答3:


You don't have to cast here, as you are copy constructing the content anyway, and the copy constructor accepts const references.

Just say:

std::vector<const Array*> obj = objects;



回答4:


If you are sure what you want to do, here is how to obtain a non-const reference to the vector.

const std::vector<const Array*> &objects;

vector<const Array*>& obj = const_cast<std::vector<const Array*>& >(objects);


来源:https://stackoverflow.com/questions/12077259/const-cast-stdvector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!