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:
Now if you are still convinced you have to, for whatever reason (like legacy API), it’s done like this:
Now
objandobjectsrefer to the same object, butobjis not const-qualified. At this point, everything is well-defined; it’s only modifying a const object that is UB, so be careful.