C++ STL容器与对象的拷贝

STL中有很多容器,当把某个类的实例存入容器时,其实是调用了相应的拷贝构造函数。
对于map这样的关系容器,如果key不存在,map调用构造函数。参考下面代码:

#include 
#include 
#include 
using namespace std;
class Test {
public:
    Test() {
        cout << "调用构造函数" << endl;
    }
    Test(const Test& t) {
        cout << "调用拷贝构造函数" << endl;
    }
    ~Test() {
        cout << "调用析构函数" << endl;
    }
};
int main(void) {
    cout << "------------------" << endl;
    vector tests;
    tests.push_back(*(new Test()));
    cout << "------------------" << endl;
    cout << "------------------" << endl;
    map testsMap;
    testsMap[1] = *(new Test());
    cout << "------------------" << endl;
    return 0;
}

你可能感兴趣的:(C++ STL容器与对象的拷贝)