I understand that const_cast to remove constness of objects is bad,
I have the following use case,
//note I cannot remove constness in the foo function foo(const std::vector<Object> & objectVec) { ... int size = (int) objectVec.size(); std::vector<Object> tempObjectVec; //Indexing here is to just show a part of the vector being //modified for (int i=0; i < (int) size-5; ++i) { Object &a = const_cast<Object&> objectVec[i]; tempObjectVec.push_back(a); } foo1(tempObjectVec); }
If i change tempObjectVec objects in foo1, will the original objects in ObjectVec change, I say yes since I am passing references, further is this efficient. Can you suggest alternatives.
Well, that depends on Object. But the Objects are being copied, when you pass them to push_back. You can check this by adding some debug code to the copy constructor. So if Object is well-behaved and keeps distinct copies separate, then foo1 can change the vector it gets all it likes.
A more efficient way to do this would be to have foo1 accept a start and end iterators:
If you don’t use const_cast, then the type system will ensure that foo1 does not change any elements, as these are const_iterators.