On May 1, 1:05 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
Dave wrote:
A quick question:
vector <T *test_vec;
T testT;
test_vec.push_back(&testT);
T * testT2p = new T;
test_vec.push_back(testT2p);
Now at the end do I need to explicitly delete the vector (test_vec).
Only the elements that were explicitly 'new'ed.
How should I make sure that the memory allocation is ok?
There is no other non-implementation-specific way except to keep
some kind of flag to distinguish between the ones you got from 'new'
and the others.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
To make things strait - you don't have to 'delete' your
test_vec since it's a stack variable. You do have to
worry about proper memory deallocation though
every time you have a collection of pointers.
One simple solution is to use std::vector<boost::shared_ptr<T.
The Boost shared pointer allows you to specify the destruction
function (that defaults to normal delete if not specified)
Wrap your stack/global object pointers with empty function,
and leave heap-allocated objects be 'delete'd.
That's almost the same as keeping the flag as above,
but moves your effort to vector insert time (when you know
where the object came from) instead of vector remove time
(when you don't.)
--
Nikolai