vector of pointers.

D

Dave

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).
How should I make sure that the memory allocation is ok?

Thanks,
 
V

Victor Bazarov

Dave said:
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
 
N

nickf3

Only the elements that were explicitly 'new'ed.


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

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.)
 
J

James Kanze

Dave said:
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).

If it is a local variable, no, but you'll have to delete
testT2p. Formally, only after the destructor of the vector has
been called.
How should I make sure that the memory allocation is ok?

Use the Boehm collector.

Otherwise, something like:

vector< T* > test_vec ;
T testT ;
test_vec.push_back( &testT ) ;
std::auto_ptr< T > testT2p( new T ) ;
test_vec.push_back( testT2p.get() ) ;

will handle this particular case.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top