STL中有很多容器,当把某个类的实例存入容器时,其实是调用了相应的拷贝构造函数。
对于map这样的关系容器,如果key不存在,map调用构造函数。参考下面代码:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class Test {
public:
Test() {
cout << "调用构造函数" << endl;
}
Test(const Test& t) {
cout << "调用拷贝构造函数" << endl;
}
~Test() {
cout << "调用析构函数" << endl;
}
};
int main(void) {
cout << "------------------" << endl;
vector<Test> tests;
tests.push_back(*(new Test()));
cout << "------------------" << endl;
cout << "------------------" << endl;
map<int, Test> testsMap;
testsMap[1] = *(new Test());
cout << "------------------" << endl;
return 0;
}
网友评论