Gandalf <gandalf@gunix.dk> writes:
Hello.
I have the following code (essential parts shown)
#include <vector>
vector<MyClass* > <v;
MyClass* obj; //baseclass for MyDerivedClassA and MyDerivedClassB
while (true)
{
if (something)
obj = new MyDerivedClassA;
else
obj = new MyDerivedClassB;
v.push_back(obj);
*********
}
Now, at the place marked with *********, do I have to/should I destroy
the object that obj points to (using delete obj). I don't want any
garbage when creating a new object when the while loop contiunes for
another round.
Well, that's the problem with storing plain "new"ed pointers in a
vector. There is no code to delete the dynamic objects when the vector
is destroyed or a pointer removed. This problem disappears if you use
a suitable smart pointer, e.g. std::vector<boost::shared_ptr<MyClass>
(see www.boost.org for details of this shared_ptr).
And exactly, how is the object inserted into the vector? I guess the
copyconstructor is used (which means that I have to supply proper copy
constructor), am I right? In that case, do I write a virtual copy
constructor, or is some typechecking done during runtime to see to that
the proper copyconstructor is called?
std::vector always copies the inserted objects. However, in this case,
the inserted object is a *pointer*, and copying a plain pointer does
not copy the referenced object.
The closest you can get to a virtual copy constructor is a virtual
"clone" method, which would look something like this (in the base
class):
virtual Base *clone () const;
or, maybe better
virtual std::auto_ptr<Base> clone();
With overrides in each base class. Of course, vector won't call this
by itself, but you could write your own handle class to do a so-called
deep copy if you needed to.
While we're at it, what does a virtual destructor look like?
If I wan't to destroy MyDerivedClassA I want at some point call the
destructor for the base class. Does it look anything like this?
MyDerivedClassA::~MyDerivedClassA(){
//Get rid of things created
//when defining the derived class
~MyClass();
}
No, the base class destructor is called automatically on completion of
the derived class destructor. The code shown would try to call it
twice.
--
Raoul Gough
"Let there be one measure for wine throughout our kingdom, and one
measure for ale, and one measure for corn" - Magna Carta
.
|