简体   繁体   中英

Array of pointers to base pointers using vector

I'm trying to add derived objects into an array of base pointers.

My class definition has the following(As this is an assignment it can not be changed):

Base** bases;

Right now I'm using an array of base pointers:

Base** bases=new Base*[2];

And adding elements like so:

bases[0]=new Derived1;
bases[1]=new Derived2;

This works fine if not for the memory leaks that I can't seem to trace. I read I can use vectors for similar purposes with better memory management.

I tried:

vector<Base*>basesV;
basesV.push_back(new Derived1);
basesV.push_back(new Derived2);

It seems to work but how do I 'attach' the vector basesV into my class Base** bases?

Simply bases=basesV; doesn't seem to work. Am I stuck using an array of base pointers?

I also have a function that takes in Base** and dropping the above vector doesn't seem to work as well.

Thanks for any help.

If I understand correctly...

bases = &basesV[0];

Also make sure your Base destructor is virtual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM