笔试遇到一个问申请对象调用的是拷贝构造函数还是默认构造函数的问题,研究了一下。
原始代码
vc2010编译器运行结果:/*几种类型申请数据构造函数的调用*/ #include <iostream> #include <vector> using namespace std; class ctest { static int defconstruct;//用于保存默认构造函数的调用次数 static int copyconstruct;//用于保存copy构造函数的调用次数 public: ctest() { ++defconstruct; cout << defconstruct << ": " << "default construct" << endl; } ctest(const ctest& copy) { ++copyconstruct; cout << copyconstruct << ": " << "copyconstruct" << endl; } }; int ctest:: defconstruct = 0; int ctest:: copyconstruct = 0; int main() { //测试编译器类型 #if defined(__GNUC__) cout << "GCC" << endl; #endif #if defined(_MSC_VER) cout << "VC" << endl; #endif ctest ctest_arry [5]; ctest *pctest = new ctest[5]; vector<ctest> vctest(5);
}
gcc(在windwows下使用的是Code Block 12.11):
结构分析:
对于数组和动态数组,vc和gcc都对每个数组成员调用n次默认构造函数。
对于顺序容器,vc对于每个成员都先调用n次默认构造函数生成临时对象(应该是),然后调用n次copy构造函数。对于gcc来说只调用一次默认构造函数,然后调用n次copy构造函数。
对于顺序容器初始化如果使用自定义类型的非默认构造函数,vc和gcc都采用调用1次带参构造函数和n次copy构造函数。