Colleagues encountered the following problem in debug:
1 Class Basic 2 { 3 Public : 4 Basic () {cout < " Basic ctor " < Endl ;} 5 Virtual ~ Basic () {cout < " Basic dtor " < Endl ;} 6 Virtual Void Foo () {cout < " Basic foo " < Endl ;}
PRIVATE:
Char data [4]; 7 }; 8 9 10 Class Deride: Public Basic 11 { 12 Public : 13 Deride () {cout < " Deride ctor " < Endl ;} 14 Virtual ~ Deride () {cout < " Deride dtor " < Endl ;} 15 Virtual Void Foo () {cout < " Deride foo " < Endl ;}
PRIVATE:
Char data [6]; 16 }; 17 18 19 Int Main () 20 { 21 22 Basic * pb = New Deride [ 20 ]; 23 24 Pb [ 1 ]. Foo ();// Correct? 25 26 Delete [] Pb; // is it correct? 27 28 Return 0 ; 29 }
The above two calls are problematic for the following reasons:
Pb [1]. Foo () includes the following aspects:
1) Pb [1] = * (Pb + sizeof (basic ));
PB actually points to the deride type memory, if sizeof (basic )! = Sizeof (deride), the Access Method of Pb [1] is not correct in deride [10.
2) Pb [1]. Foo (), Foo () is virtual. To call a function, you need to access the virtual function table.
3) In general, the vptr is put in a fixed position by default, such as the beginning of the class. Therefore, only when the pointer of the current object is obtained correctly can the vptr be obtained correctly.
Based on the above three analyses, we can draw the following conclusions:
1) Pb [1]. Foo ()CodeIs incorrect.
2) Delete [] Pb is also incorrect.