Search code examples
c++copydepth

issues related to the copy of vector with pointer item


I want to ask whether there are some problems with the copy for the vector of pointer items. Do I need to strcpy or memcpy because there may be depth copy problem?

For instance:

Class B;

Class A

{
   ....

private:
   std::vector<B*> bvec;

public:

   void setB(std::vector<B*>& value)

   {

      this->bvec = value;

   }

};

void main()

{

   ....

   std::vector<const B*> value; // and already has values

   A a;

   a.setB(value);

}

This example only assign the value to the class variable bvec inside A class. Do I need to use memcpy since I found that std::vector bvec; has pointer items? I am confused with the depth copy in C++, could you make me clear about that? Thank you.


Solution

  • It is unlikely you need strcpy or memcpy to solve your problem. However, I'm not sure what your problem is.

    I will try to explain copying as it relates to std::vector.

    When you assign bvev to value in setB you are making a deep copy. This means all of the elements in the vector are copied from value to bvec. If you have a vector of objects, each object is copied. If you have a vector of pointers, each pointer is copied.

    Another option is to simply copy the pointer to the vector if you wish to reference the elements later on. Just be careful to manage the lifetimes properly!

    I hope that helps!