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 ?
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.