C ++ object placement

zhaozj2021-02-08  252

(Disclaimer: This article refers to the book "Deep Exploration C Object Model", I have even an example, if someone thinks is to steal, please forgive, ^ _ ^) experience from C to C , I want to know how the C compiler is scheduled for members. Here I am probably introduced, and some code is for you to test, I hope to have a bit a bit for everyone. In fact, the title here may be a bit big, simple Say, the non-Static member of the class is stored in the memory area in order, and the class Static member is the same as the general STATIC variable. I don't start from a simple thing, directly from a relatively complex multiple inheritance. The example starts. Look at the following code: Class Point2d {public: int _x, _y; virtual f () {} // guarantee that Point2D has a virtual pointer}; Class Point3d: public point2d {public: int_z;}; Class Vertex {public: Virtual Void H () {} // guarantees the second basic class of Vertex3D has a vptr int next;}; class vertex3d: public point3d, public vertex {public: int mumble;}; point2d, point3d, vertex, Vertex3D The inheritance relationship can be seen. Look at the main function int main () {Vertex3D V3D; Vertex * PV; PV = & V3D; int * x = & v3d._x; // Get address INT * Y = & V3D ._y; int * z = & v3d._z; int * n = & v3d.next; int * MEM = & v3d.mumble; cout << "* v3d =" << & v3d << endl; // output first VPTR COUT << "* x =" << x << Endl; // Output member's x address cout << "* y =" << "endl; // .... cout <<" * z = "<

0x0012FF7C is seen from the output of the above output, how is the object, if you don't believe, you can try it yourself, output the size of Vertex3D, ^ _ ^. Note, Vertex3D has two VPTR If you still don't know why there will be, I suggest you go first !! Supplement: I think another intuitive method is to use the Placement Operator New (Pon) method, and there is a Placement Operator delete As for these concepts, I don't have much to say, ^ _ ^. Just see those addresses are in memory, but they can use (PON) to put those addresses in a array, which will be more intuitive, do not believe, You look: #include #include Class Point2d {public: int _x, _y; // point2d () {_x = 10; _y = 20;} Virtual f ()}} Class Point3d: public point2d {public: int_z; point3d () {_ z = 30;}}; class valuex {public: int next; vertex () {next = 40;} Virtual void f () {} Virtual Void G () {} Virtual Void H () {}}; Class Vertex3d: Public Point3D, Public VertEx {public: int Mumble; Vertex3d () {Mumble = 50;}}; int main () {long str [30]; vertex3d * array = new (STR) Vertex3D; for (int i = 0; i

转载请注明原文地址:https://www.9cbs.com/read-2728.html

New Post(0)