简体   繁体   中英

Dynamic memory and inherited structs in C++

Say I have some structs like this:

struct A{
 int someInt;
}

struct B : public A{
 int someInt;
 int someOtherInt;
}

And a class:

class C{
 A *someAs;
 void myFunc(A *someMoreAs){
  delete [] someMoreAs;
 }
}

would this cause a problem:

B *b=new B[10];
C c;
c.myFunc(b);

Because it's deleting b, thinking that it's of type A, which is smaller. Would this cause a memory leak?

Also, say I want to allocate more of the same as b within myFunc, using new, but without C knowing whether b is of A or B? A friend sugegsted typeof, but VC doesn't seem to support this.

No memory will leak in this particular case because both A and B are POD (plain old data) and thus their contents do not require any destruction.

Still, it is a good practice to always have a virtual destructor in a (base) class that is supposed to be inherited from. If you add a virtual destructor to A , any deletion via A* will call the proper derived destructors too (including destruction of derived classes' members).

virtual ~A() {}

Notice, however, that you cannot use inheritance in arrays of base type, precisely because the actual size of the objects might differ.

What you really want is probably an array of pointers to base class:

std::vector<A*> someAs;

Or the Boost equivalent (with automatic memory management and nicer API):

boost::ptr_vector<A> someAs;

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