What does a C ++ compiler do to create an object?

In C code, like:

{
   int i = 5;
   /* ....... */
}

The compiler will replace the code by moving the stack pointer down (for stacks growing down) by the size int and places the value 5 in this memory location.

Similarly, in C ++ code, what does the compiler do if the object is created? For example:

class b
{
   public :
           int p;
           virtual void fun();
};

main()
{
   b   obj;
}

What will the compiler do for the above code? Can someone explain when the memory is allocated, and when the memory is allocated for the virtual table and when the default constructor is called?

+3
source share
6 answers

In designs

Logically, there is no difference between the two:

In both cases, the stack is made large enough to hold the object, and the constructor is called on the object.

:

  • POD .
  • .

:

int   x;  // stack frame increased by sizeof(int) default construct (do nothing)
B     a;  // stack frame increased by sizeof(B)   default construct.

:

int   y(6);  // stack frame increased by sizeof(int) Copy constructor called
B     b(a);  // stack frame increased by sizeof(B)   Copy constructor called

Ok. , POD , ( ), , , .

. ( , ), POD, - .

:

, , .
vtable . , vtable, , ( ). vtable.

. , vtable , , . , vtable, , , , , .

. /. , , , , vtable , .

+6

, ( , ) sizeof b, .

, ( , ), , , int, , . , , (, &).

+3

. ( ).

. - . .

- .

+2

   b   obj;

int, b. . . b. .

vftable - . . "" , vftable. sizeof (b).

+1

, , , , , . , -, (, , ).

0

Itanium ++ ABI (, , GCC ), , .

, _ZTV5Class. , Class . , , .

, , , .

0

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


All Articles