Address: http://www.cppblog.com/vczh/archive/2013/04/27/199765.html
Posted on Chen zihan (vczh)
The hole in the pointer of C ++. The remaining pitfalls are left in the next article. If I was not asked in the fan group, I still don't know that someone would do this:
class Base{ ...};class Derived : public Base{ ...};Base* bs = new Derived[10];delete[] bs;
I would like to say that this is completely C ++ compatible with C language, and then the C language is pitfall. In fact, this problem does not occur in the C language, because the C language pointer actually has only one: char *. Many C-language functions accept char * and void * is only available later. The malloc and free operations for pointers in C language are actually reading it as char. So when you malloc something, cast it into the type you need, and finally free it, the existence of cast in this step does not exist, it is no difference whether free can be correctly executed.
But it is different when it comes to C ++. C ++ has inheritance. If it has inheritance, it has implicit type conversion of pointers. Let's look at the code above. We have a new [] pointer of the derived * type, and then implicitly converted it to base *. Finally, we use his Delete [] Because Delete [] needs to call the destructor, however, the base * type pointer cannot correctly calculate the position of the this pointer required by the ten destructor of the derived array. Therefore, the code is finished at this time (if it is not enough, that's just a coincidence ).
To be compatible with the C language, the "new [] pointer must be deleted []" and the "sub-class pointer can be converted to the parent class Pointer" rules are successfully conflicted. In fact, if you need to solve this problem, how should you change the type? In fact, we can introduce the derived [] pointer type like C. This is what comes out of new []. In C ++, delete [] can also be required, but the difference is that it can no longer be converted to base. Unfortunately, t [] is occupied by C language and used as T * in the function parameter type. C language is a waste of syntax ......