const_cast std::vector

2019-07-21 16:00发布

问题:

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