Let's say I have this:
SolutionSet(const SolutionSet &solutionSet) {
this->capacity_ = solutionSet.capacit开发者_StackOverflow社区y_;
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..)?
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).
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.
精彩评论