You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何向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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 14:12:05