我最近阅读了简单的STL源代码,以下是代码:
#include <iostream>
#include <cstddef>
using namespace std;
class alloc
{
};
template <typename T, typename Alloc = alloc, size_t Bufsiz = 0>
class deque
{
public:
deque() { cout << "deque()" << endl; }
};
template <typename T, typename Sequence = deque<T> >
class stack
{
public:
stack() { cout << "stack()" << endl; }
private:
Sequence c;
};
int main()
{
stack<int> x;
return 0;
}
输出:
deque()
stack()
当我创建一个堆栈对象时,它应该首先调用堆栈构造函数。但事实并非如此。
为什么编译器首先调用deque构造函数?
答案 0 :(得分:4)
在输入构造函数的主体之前,会调用基类构造函数,然后所有非静态成员变量都按声明的顺序进行默认初始化,除非它们出现在成员初始化列表中。在您的代码Sequence c
首先进行初始化,然后执行Stack::Stack()
的正文。
这个程序说明了施工的顺序 - 破坏。
#include <iostream>
#include <string>
using namespace std;
struct Base_1
{
Base_1()
{
cout << "Base_1\n";
}
~Base_1()
{
cout << "~Base_1\n";
}
};
struct Base_2
{
Base_2()
{
cout << "Base_2\n";
}
~Base_2()
{
cout << "~Base_2\n";
}
};
struct Member_1
{
Member_1()
{
cout << "Member_1\n";
}
~Member_1()
{
cout << "~Member_1\n";
}
};
struct Member_2
{
Member_2()
{
cout << "Member_2\n";
}
~Member_2()
{
cout << "~Member_2\n";
}
};
struct Member_non_default
{
Member_non_default( string s )
{
cout << "Member non default\n";
}
~Member_non_default()
{
cout << "~Member non default\n";
}
};
struct Static_member
{
Static_member()
{
cout << "Static member\n";
}
~Static_member()
{
cout << "~Static member\n";
}
};
struct Derived: Base_1, Base_2
{
Member_1 m1;
Member_non_default m;
Member_2 m2;
static Static_member sm;
Derived():
m { "Member non default\n" }
{
cout << "Derived\n";
}
~Derived()
{
cout << "~Derived\n";
}
};
Static_member Derived::sm;
int main()
{
Derived d;
}
输出
静态成员
Base_1
Base_2
MEMBER_1
会员非默认
MEMBER_2
派生
〜衍生
〜MEMBER_2
〜会员非默认
〜MEMBER_1
〜Base_2
〜Base_1
〜静态成员