does vector<>.resize call delete?

J

john smith

Hi, when there is a vector<> of pointers to some objects, does calling
resize cause vector to call delete on each object, or is there a memory leak
problem?

for example:

struct base {//some vars; ~base();};
vector<base*> vb;
vb.push_back(new base);
vb.push_back(new base);
vb.push_back(new base);
vb.push_back(new base);

vb.resize(12); // cause memory leak here?

Thanks in advance.

S
 
K

Kevin Goodsell

Victor said:
'resize' will copy the first four elements and then create and
default-initialise (zero-initialise, in case of pointers) eight
more objects.

Victor, is that the right terminology? I believe Accelerated C++ uses
the term "value-initialize" for what happens it this case.
"default-initialization" would leave built-in types undefined (unless
they are static). Or am I mistaken?

-Kevin
 
J

John Harrison

john smith said:
Hi, when there is a vector<> of pointers to some objects, does calling
resize cause vector to call delete on each object, or is there a memory leak
problem?

for example:

struct base {//some vars; ~base();};
vector<base*> vb;
vb.push_back(new base);
vb.push_back(new base);
vb.push_back(new base);
vb.push_back(new base);

vb.resize(12); // cause memory leak here?

Thanks in advance.

S


You chose a bad example. But vector will *never* call delete on the pointers
you put into it. Think about it, how could vector know that you allocated
the pointers using new? All pointers look the same whether they've been
allocated with new, malloc or not allocated at all.

This is why a vector of pointers is a bad idea (in general). Learn about
smart pointers instead.

john
 

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

No members online now.

Forum statistics

Threads
474,139
Messages
2,570,805
Members
47,351
Latest member
LolaD32479

Latest Threads

Top