Inheritance and duplicating items on an STL vector

Started by
2 comments, last by Zahlman 14 years, 5 months ago
Hello. I need to make a duplicate of an instance of a class which is held on an STL vector and put it onto another STL vector. The class inherits from a base class which is used when declaring the vectors:

std::vector<Maneuver*> maneuvers;								
std::vector<Maneuver*> requestedmaneuvers;

Maneuver is the base class of which several variants are derived from, and then added to these two lists like such:

maneuvers.push_back( new AIManeuverFlank ); 

To copy one of the instances on maneuvers vector to the requestedmaneuvers vector, I do this:

BYTE * temp = new BYTE[ maneuvers-&gt;GetSize() ];
memcpy( temp, maneuvers, maneuvers-&gt;GetSize() );
requestedmaneuvers.push_back( (Maneuver*) temp ); 

</pre></div><!–ENDSCRIPT–>


GetSize() gives the size of the derived class, because sizeof( *maneuvers ) seems to return the size of the base class &#111;nly.

Thus far this works ok but seems sloppy. My question is whether this is acceptable practice, or is there a simpler method to perform this copy? I don’t need to worry about any dynamic containers that might be members either the base or derived classes.

Thanks for reading,
Jackson Allan
Advertisement
Quote:Original post by jack_1313
To copy one of the instances on maneuvers vector to the requestedmaneuvers vector, I do this:
*** Source Snippet Removed ***

That really doesn't seem safe. It looks like you are copying everything, including the 'this' pointer which seems very unsafe and begging for trouble. The typical solution to the problem of making a copy of a derived class when all you know is the base class you can use a clone member function. The C++ FAQ Lite has you covered with the concept and roughly how you would implement it in your code. This method is more elegant, safe, and idiomatic than what you are doing.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

Thanks nobodynews, that was very concise.

Jackson Allan
Quote:Original post by nobodynews
Quote:Original post by jack_1313
To copy one of the instances on maneuvers vector to the requestedmaneuvers vector, I do this:
*** Source Snippet Removed ***

That really doesn't seem safe. It looks like you are copying everything, including the 'this' pointer which seems very unsafe and begging for trouble.


"The 'this' pointer" is not (except possibly on some obscure debugging implementation" part of the data layout of an object. However, there may be all sorts of other stuff that is not safe to copy (such as a vtable, or pointers that ought to be deeply copied), especially if the class is polymorphic.

This topic is closed to new replies.

Advertisement