Const_cast for a vector with an object

I understand that const_cast to remove object constants 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 to foo1, will the original objects change in ObjectVec, I say yes, because I pass the links, this is effective in the future. Can you suggest alternatives.

+1
source share
4 answers

Well, it depends on the object. But objects are copied when you pass them push_back. You can verify this by adding debug code to the copy constructor. Therefore, if Object behaves well and saves separate copies separately, then foo1 can change the vector, which gets everything he likes.

, foo1 :

void foo1(std::vector<Object>::const_iterator start,
          std::vector<Object>::const_iterator end);

...
foo1(objectVec.begin(), objectVec.end() - 5);

const_cast, , foo1 , const_iterators.

+3

tempObjectVec , , :

std::vector<Object> tempObjectVec;

tempObjectVec.push_back(a) , tempObjectVec. , const_cast , , .

+1

, , :

const_cast<std::vector<Object>&> (objectVec) std::vector, foo1 ( ).

:

foo(const std::vector<Object> & objectVec) {

    ...
    foo1(const_cast<std::vector<Object> &>(objectVec));
}

foo1, , , , , , Object.

+1

, push_back , , . , objectVec[i] tempObjectVec.

, ( , , ), . . . . , - . boost pointer container, , .

+1

Source: https://habr.com/ru/post/1777635/


All Articles