C ++ compilers will not generate a default constructor class constructor do? (When it is necessary to generate, depending on the situation. There disassembly verification)

Before the C ++ class time, the impression that there are so sentence:
If a class has no constructor, the compiler will generate a default constructor

In the second chapter today to see the "depth exploration of C ++ object model": "The constructor semantics," I find heard before is wrong.

For example, the following code:

class A {
public:
int a;
};

main int (void) {
A A;
AA =. 4;
A A2;
a2.a =. 5;
return 0;
}
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
in accordance with the previous statement, no constructor class A, the compiler automatically generates a default constructor, but it is not. The above code can see the results after disassembly:

main:
Push RBP
MOV RBP, RSP #int main (void)
MOV DWORD the PTR [-RBP. 4], = #AA. 4. 4;
MOV DWORD the PTR [-RBP. 8], # a2.a =. 5. 5;
MOV EAX, 0 0 #return;
POP RBP
RET
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
we can see that objects of this class is directly used, and does not call any constructors, there is no initialization.

According to a statement on the "depth exploration of C ++ Object Model" book, the compiler needs only when certain default constructor, the default constructor will be created, for example:

class A {
public:
A () {A = 0;}
int A;
};
class B: public A {
A _tmp;
};
int main (void) {
B B;
return 0;
}
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
when object initialization class B, class a class object exists need default constructor initializes the object B, then object B class must have a default constructor, the compiler creates a compelling in the case of default constructor class B object.
Disassembly you can see the default constructor class B:

A::A() [base object constructor]:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi
mov rax, QWORD PTR [rbp-8]
mov DWORD PTR [rax], 0
nop
pop rbp
ret
B::B() [base object constructor]:
push rbp
mov rbp, rsp
sub rsp, 16
mov QWORD PTR [rbp-8], rdi
mov rax, QWORD PTR [rbp-8]
mov rdi, rax
call A::A() [base object constructor]
mov rax, QWORD PTR [rbp-8]
add rax, 4
mov rdi, rax
call A::A() [complete object constructor]
nop
leave
ret
main:
push rbp
mov rbp, rsp
sub rsp, 16
lea rax, [rbp-8]
mov rdi, rax
call B::B() [complete object constructor]
mov eax, 0
leave
ret

----------------
Disclaimer: This article is the original article CSDN bloggers "zhangpeterx", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement. .
Original link: https: //blog.csdn.net/zhangpeterx/article/details/102762410

Guess you like

Origin www.cnblogs.com/findumars/p/11809686.html