C++ destruction list
I have a class to do a computation using some callbacks. those callbacks need to allocate data (dynamic arrays) that needs to live outside of the callback scope but not after the cla开发者_JAVA百科ss destructs. I thought about make a vector
of auto_ptr
that will just get destructed automatically when the class destructs:
class MyClass
{
vector<auto_ptr<MyObject>> ThingsToDie;
};
The problem is I have a lot of objects allocated and they don't share a base type so I can't use one vector
for this, and making a vector for every type is a lot of work.
auto_ptr_base (virtual destructor)
|
auto_ptr<T>
Will solve my problem because I could do something like
class MyClass
{
vector<auto_ptr_base> ThingsToDie;
};
and the destruction will be virtually dispatched to each specialized type automatically.
The problem is that the STL doesn't have that hierarchy and I don't want to re-implement auto_ptr. Is there any other solution for this?You could use a vector<shared_ptr<void>>
.
Read this: Why do std::shared_ptr<void> work
精彩评论