前言
通过汇编查看构造函数调用构造函数的调用路径
先查看直接调用的结果
#include <iostream>
using namespace std;
struct Person {
int m_age;
int m_height;
Person() {
Person(10, 20);
}
Person(int age,int height) {
m_age = age;
m_height = height;
}
};
int main()
{
Person person;
cout << person.m_age << endl;
cout << person.m_height << endl;
getchar();
return 0;
}
out为
-858993460
-858993460
查看汇编
27: Person person;
00A71AE2 lea ecx,[person]
00A71AE5 call Person::Person (0A71546h)
Person::Person:
00A71546 jmp Person::Person (0A71A50h)
10: Person() {
00BD1A50 push ebp
00BD1A51 mov ebp,esp
00BD1A53 sub esp,0DCh
00BD1A59 push ebx
00BD1A5A push esi
00BD1A5B push edi
00BD1A5C push ecx
00BD1A5D lea edi,[ebp-0DCh]
00BD1A63 mov ecx,37h
00BD1A68 mov eax,0CCCCCCCCh
00BD1A6D rep stos dword ptr es:[edi]
00BD1A6F pop ecx
00BD1A70 mov dword ptr [this],ecx
00BD1A73 mov ecx,offset _BE606A61_ConsoleApplication2@cpp (0BDF029h)
00BD1A78 call @__CheckForDebuggerJustMyCode@4 (0BD1406h)
11: Person(10, 20);
00BD1A7D push 14h
00BD1A7F push 0Ah
00BD1A81 lea ecx,[ebp-0D8h] //是将一个临时的地址值(并不是[person])传给有参构造函数的this
00BD1A87 call std::endl<char,std::char_traits<char> > (0BD153Ch)
12: }
构造函数调用构造函数必须写在初始化列表中
#include <iostream>
using namespace std;
struct Person {
int m_age;
int m_height;
Person():Person(10, 20) {
}
Person(int age,int height) {
m_age = age;
m_height = height;
}
};
int main()
{
Person person;
cout << person.m_age << endl;
cout << person.m_height << endl;
//getchar();
return 0;
}
out为
10
20
查看汇编
27: Person person;
00691AE2 lea ecx,[person] //将person对象的地址[person]传给ecx
00691AE5 call Person::Person (0691546h)
Person::Person:
00691546 jmp Person::Person (0691A50h)
10: Person():Person(10, 20) {
00691A50 push ebp
00691A51 mov ebp,esp
00691A53 sub esp,0CCh
00691A59 push ebx
00691A5A push esi
00691A5B push edi
00691A5C push ecx
00691A5D lea edi,[ebp-0CCh]
00691A63 mov ecx,33h
00691A68 mov eax,0CCCCCCCCh
00691A6D rep stos dword ptr es:[edi]
00691A6F pop ecx
00691A70 mov dword ptr [this],ecx //将ecx传给无参构造函数Person()的this
00691A73 mov ecx,offset _BE606A61_ConsoleApplication2@cpp (069F029h)
00691A78 call @__CheckForDebuggerJustMyCode@4 (0691406h)
00691A7D push 14h
00691A7F push 0Ah
00691A81 mov ecx,dword ptr [this] //可以看出无参构造函数和有参构造函数的this指向的都是[person]
//查看地址信息也能发现,此时ecx中存储的地址是[person],如下图所示
00691A84 call std::endl<char,std::char_traits<char> > (069153Ch)
11:
12: }
std::endl<char,std::char_traits<char> >:
0079153C jmp Person::Person (0791FA0h)