Re: Cannot delete created library object
On Sun, 16 Jul 2006 11:33:52 +0200, Christian Christmann
<plfriko@yahoo.de> wrote:
in my source code I've included a library I've not written and source code
is available.
In a function, I've generate an object of that library class dynamically
with "new" and at the function's end I want to freed memory for that
object with "delete". However, doing that seem to be not allowed since
I get the compiler error:
error: `virtual LibraryClass::~LibraryClass()' is protected
myfile.cc:1000: error: within this context
There are two common situations where this may arise. Since I was
deliberately misinterpreted in a subtread I give two examples of what
might have happened.
1. The class uses 'implementation' inheritance. To prevent derived
objects from being used polymorphically the base class destructor (and
constructor) are made protected. Implememtaton inheritance is
typically used for value types, i.e. small objects with value
semantics that are created on the stack:
class ValueImp{
protected:
ValueImp() {}
~ValueImp() {}
// ...
};
class Value : public ValueImp{
};
int main() {
ValueImp* p = new Value();
delete p; // error
}
2. The dynamically created object is managed (created, owned, deleted)
by another object. This idiom simplifies resource management issues
because allocation and deallocation disappear from the surface level
of your code. Again, a protected or private destructor inhibits
unintended behavior:
class Manager;
class ManagedObject {
protected:
~ManagedObject() {}
friend class Manager;
};
class Manager {
public:
Manager() {}
~Manager() {
while (!container.empty()) {
ManagedObject* tmp = container.back();
container.pop_back();
delete tmp;
}
}
ManagedObject* create() {
ManagedObject* p = new ManagedObject();
container.push_back (p);
return p;
}
private:
std::vector<ManagedObject*> container;
// non copyable
Manager (const Manager&);
Manager& operator= (const Manager&);
};
int main() {
Manager m;
ManagedObject* p = m.create();
delete p; // error
}
Best wishes,
Roland Pibinger