0

Let's say I have this:

SolutionSet(const SolutionSet &solutionSet) {
    this->capacity_ = solutionSet.capacity_;
    this->solutionsList_ = solutionSet.solutionsList_; // <--
}

And solutionsList_ is a vector<SomeType*> vect*. What is the correct way to copy that vector (I suppose that way I'm not doing it right..)?

dmessf
  • 1,025
  • 3
  • 11
  • 19
  • 1
    And furthermore, why are you storing pointers in the vector instead of objects? It's generally a good idea _not_ to store raw pointers in a standard library container; you should prefer to use a pointer container (like those provided by the Boost library) or store smart pointers in the container. – James McNellis Apr 17 '10 at 00:58
  • Boost Pointer Containers: http://www.boost.org/doc/libs/release/libs/ptr_container/doc/ptr_container.html –  Apr 17 '10 at 01:01
  • Related question (getting an answer there will clear up some ambiguity with this question): http://stackoverflow.com/questions/2656700/c-pointers-objects-etc –  Apr 17 '10 at 01:04
  • @James McNellis: some types of smart pointer, such as auto_ptr, are not safe to store in STL containers. – Beta Apr 17 '10 at 01:06
  • I misread the vect type in the first revision, what you have now indeed doesn't make sense. What is the type of vect? –  Apr 17 '10 at 01:12

2 Answers2

0

What you do now is a "shallow copy" of your solutions list - the original vector contains a list of references to solutions, and the copied vector will contain references to the same solutions. It might be exactly what you need here.

If it is not and you really need a deep copy, i.e. you would like to have every solution duplicated when creating a second solutionset, you will need to ensure your SomeType has a well-defined copy constructor and then either manually walk through all items in the new vector and do the copying:

for (int i = 0; i < solutionsList.size(); i++) 
     solutionsList[i] = new SomeType(solutionsList[i]);

or use pointer containers, as suggested already (which might be an overkill though).

KT.
  • 10,815
  • 4
  • 47
  • 71
0

vector<SomeType*> vect*. What is the correct way to copy that vector [...]?

The correct way would be to not to have dumb pointers to dynamically allocated objects. Make this a smart pointer and it all becomes much easier.

sbi
  • 219,715
  • 46
  • 258
  • 445