C ++ std :: vector in constructor

I am trying to code an efficient implementation of the following composite class:

class composite{ vector<base_class *> Vec; //Other useful constants public: composite(vector<base_class*>); //Other useful operations... }; 

My question is about the constructor and instance of the class, and in particular the Vec object. At this point, I am using a rather crude implementation described below. I am an implementation to be effective memory. I am pretty much new with C ++, so I'm not sure if I have an optimal solution here ...

I use polymorphism to store various derived classes in a vector, for example.

 vector<base_class *> Vec1; Vec1.reserve(2); class1 * C1 = new class1(....); Vec1.push_back(C1); class2 * C2 = new class(....); Vec1.push_back(C2); 

where class1 and class2 are derived classes of base_class. Then I pass Vec1 to the composite constructor as follows:

 composite::composite(vector<base_class*> Vec1){ Vec.reserve(Vec1.size()); Vec.swap(Vec1); //etc... } 

I feel this is pretty memory efficient because Vec1 will be empty after building (its elements have been replaced with Vec). On the other hand, this seems rather wasteful, as I essentially copy Vec1 to Vec. Is there a better way for me to do this? Can I somehow insert the Vec1 vector into a composite? Thanks in advance!

+1
c ++ polymorphism constructor vector std
source share
2 answers

First use the correct smart pointer instead of the raw pointer.

Next - in the method you use, the call to reserve() completely unnecessary - swap() just swaps the internal pointers.

And the last - since we are in 2013, C ++ 11 will already be used, so the constructor should look like this:

 composite::composite(std::vector<std::unique_ptr<base_class>> v) : vec{ std::move(v) } { } 

Why is that? Taking the parameter by value, it already copies it, and since you are no longer going to use this copy, it is safe to transfer it, which allows you to get the least number of copies to initialize the member.

+3
source share

If you are really interested in whether a copy of any vector will be made, you must first pass the constructor argument by reference. Thus, a โ€œregularโ€ implementation will look like this:

 composite::composite( const vector<base_class*>& Vec1 ) : Vec( Vec1 ) { } 

This will drop one copy already. I would not worry about this until you have signs that this will cause any problems. You have already done three dynamic memory allocations before, why do you care about the fourth?

+1
source share

All Articles