Dynamic memory and inherited structures in C ++

Let's say I have structures like this:

struct A{
 int someInt;
}

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

And the class:

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

this will cause a problem:

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

Because he removes b, thinking it is type A, which is smaller. Will this lead to a memory leak?

Also, let's say I want to highlight more than b in myFunc using the new one, but without C, knowing whether b is A or B? Friend is sugegsted typeof, but VC doesn't seem to support this.

+3
source share
1 answer

In this particular case, no memory will leak out because both A and B are POD (plain old data), and therefore their contents do not need to be destroyed.

, () , . A, A* ( ).

virtual ~A() {}

, , , , .

, , , :

std::vector<A*> someAs;

Boost ( API):

boost::ptr_vector<A> someAs;
+4

Source: https://habr.com/ru/post/1733425/


All Articles