为何向std::vector中push对象时会调用拷贝构造函数?
#include <iostream> #include <vector> class Car{ public: int weight; Car(int weight): weight(weight){ }; Car(const Car& other){ std::cout<<"copied!"<<std::endl; this->weight=other.weight; } }; int main() { std::vector<Car> vec; vec.push_back(Car(1)); return 0; }
问题
在上述代码中,执行vec.push_back(Car(1))向std::vector<Car>推入对象时,Car类的拷贝构造函数被调用。明明未显式执行拷贝操作,请问该现象的原因是什么?
原因解析
- 临时对象的拷贝行为:
Car(1)是一个临时创建的右值对象,在C++11之前的标准中,push_back方法会将这个临时对象的内容完整拷贝到vector内部的存储空间中,这个过程就会触发拷贝构造函数。 - vector的内存管理逻辑:vector的底层是动态分配的连续内存,当你首次调用
push_back时,vector会先分配一块初始内存,然后必须通过拷贝构造的方式,把外部对象(这里是临时对象)的数据复制到自己管理的内存区域里,完成对象的存储。
补充:如果你的代码基于C++11及以后标准,可以给Car类添加移动构造函数,此时push_back会优先调用移动构造来转移临时对象的资源,避免不必要的拷贝开销:
Car(Car&& other) noexcept { std::cout << "moved!" << std::endl; this->weight = other.weight; }
内容的提问来源于stack exchange,提问作者simply lemon
相关产品推荐
相关产品推荐

