Je voudrais implémenter une copie de std::stack< boost::shared_ptr<T> >
. Y at-il un moyen de le faire sans 3 copies? Voici le code:Copie en profondeur de std :: stack <boost> shared_ptr <T>>
template<typename T>
void copyStackContent(std::stack< boost::shared_ptr<T> > & dst,
std::stack< boost::shared_ptr<T> > const & src){
//// Copy stack to temporary stack so we can unroll it
std::stack< boost::shared_ptr<T> > tempStack(src);
/// Copy stack to array
std::vector< boost::shared_ptr<T> > tempArray;
while(!tempStack.empty()){
tempArray.push_back(tempStack.top());
tempStack.pop();
}
/// Clear destination stack
while(!dst.empty()){
dst.pop();
}
/// Create destination stack
for(std::vector< boost::shared_ptr<T> >::reverse_iterator it =
tempArray.rbegin(); it != tempArray.rend(); ++it){
dst.push(boost::shared_ptr<T>(new T(**it)));
}
}
et un test de l'échantillon:
void test(){
// filling stack source
std::stack< boost::shared_ptr<int> > intStack1;
intStack1.push(boost::shared_ptr<int>(new int(0)));
intStack1.push(boost::shared_ptr<int>(new int(1)));
intStack1.push(boost::shared_ptr<int>(new int(2)));
intStack1.push(boost::shared_ptr<int>(new int(3)));
intStack1.push(boost::shared_ptr<int>(new int(4)));
// filling stack dest
std::stack< boost::shared_ptr<int> > intStack2;
copyStackContent(intStack2, intStack1);
assert(intStack1.size() == intStack2.size()); // same size
while(!intStack1.empty()){
assert(intStack1.top() != intStack2.top()); // != pointers
assert((*intStack1.top()) == (*intStack2.top())); // same content
intStack1.pop();
intStack2.pop();
}
}
La pile de destination devrait probablement être retournée par valeur au lieu d'utiliser une cible. +1 –
Eh bien, mon T doit être aligné lorsqu'il est alloué, donc il n'utilise pas vraiment un nouveau, mais plutôt un allocateur spécifique. – tibur
Ne devrait-il pas y avoir un tempArray.reserve (src.size()) avant la première copie? Ou serait-ce une optimisation prématurée? – Basilevs