class MD {
MD();
MD(const MD &obj);
MD& operator=(const MD &obj);
private:
int Name;
double sal;
};
typedef std::shared_ptr<MD> mDataPtr;
typedef std::vector<mDataPtr> mDataVecContr;
typedef std::shared_ptr<mDataVecContr> ptrMdataVecContr;
class MDataContainer{
public:
MDataContainer();
MDataContainer(const MDataContainer &mDataCont);
MDataContainer& operator=(const MDataContainer &mDataCont);
private:
mDataVecContr vecNode;
std::deque<ptrMdataVectContr> mDataQueContr;
};
My requirement is to store 500 object of type MD in a vector then I am keeping pointer to these vectors in deque. The problem here is how to initialize this list in copy contructor MDataContainer(const MDataContainer &mDataCont) and assign it in overloaded assignment operator MDataContainer& operator=(const MDataContainer &mDataCont). To get rid of code duplication I am using Init function. Pls explain me a method which can give better performanc开发者_开发百科e. Some rough way I am already using. Can we have some algo or some other library(boost I am not having gr8 idea) which can be used to solve this kind of problem.
You may want to reconsider your design if you want a deep copy. If you have a deque containing 10(arbitrarily picked number) shared pointers to vectors of 500 shared pointers of MD objects, a copy constructor is going to require 5021 allocations from the heap, minimum, which is going to be bulky. Are you sure you need smart pointers to the vectors, and to the MD objects? If not, the number of allocations could be brought down to 11 with std::deque<std::vector<MD>> mDataQueContr;
If you do want the deep copy with smart pointers, you'll have to loop through to construct them, as copy constructing a shared_ptr will be a shallow copy. I haven't looked into shared_ptr yet, but assuming they work like auto_ptr, you want something like this. I use iterators, because they're faster than indexing on deque.
MDataContainer::MDataContainer(const MDataContainer &mDataCont) {
// initialize the deque to default null shared pointers
mDataQueContr.resize(mDataCont.mDataQueContr.size());
// for each super smart pointer
std::dequeue<ptrMdataVectContr>::iterator destsup = mDataQueContr.begin();
std::dequeue<ptrMdataVectContr>::const_iterator srcsup;
srcsup = mDataCont.mDataQueContr.begin();
for( ; destsup != mDataQueContr.end(); ++destsup,++srcsup) {
// assign it a new vector of the right size of null shared pointers
*destsup = new mDataVecContr((*srcsup)->size());
// for each sub smart pointer
mDataVecContr::iterator destsub = (*destsup)->begin();
mDataVecContr::const_iterator srcsub = (*srcsup)->begin();
for( ; destsub != (*destsup)->end(); ++destsub,++srcsub)
*destsub = new MD(**srcsub); //assign it a new MD copy
}
精彩评论