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

如何向vector中插入包含std::condition_variable成员的自定义类?

问题原因与修复方案

错误根因

std::condition_variable 是C++标准库定义的系统级同步原语,它本身不支持拷贝、也不支持移动操作,标准库显式删除了它的拷贝/移动构造函数、拷贝/移动赋值运算符。
你的自定义类 LockRequestQueue 包含了std::condition_variable 类型的非静态成员,因此编译器会自动删除该类的默认拷贝构造、拷贝赋值、移动构造、移动赋值函数。
你调用的 vecs.push_back(request) 传入的是左值request,底层需要调用LockRequestQueue的拷贝构造函数,函数不存在就会触发编译报错。删除cv_成员后类的默认拷贝函数可用,所以运行正常。

可行修复方案

  • 方案1:vector存储智能指针而非对象本身
    不需要修改原类定义,只需要修改vector的声明和插入逻辑,避免对象拷贝,是最常用的无侵入方案:
    int main(){
        auto request = std::make_unique<LockRequestQueue>();
        std::vector<std::unique_ptr<LockRequestQueue>> vecs;
        vecs.push_back(std::move(request));
        // 如果不需要保留原request变量,也可以直接原地构造
        // vecs.emplace_back(std::make_unique<LockRequestQueue>());
        return 0;
    }
    
  • 方案2:为自定义类手动实现拷贝/赋值函数
    如果你的业务逻辑允许拷贝LockRequestQueue对象(注意:拷贝生成的新对象的条件变量是全新实例,和原对象的条件变量无关联,等待在原对象条件变量上的线程不会收到新对象的通知,业务逻辑需要兼容该语义),可以手动实现拷贝相关函数,显式忽略cv_的拷贝:
    class LockRequestQueue {
     public:
      LockRequestQueue() = default;
      // 手动实现拷贝构造
      LockRequestQueue(const LockRequestQueue& other) 
          : request_queue_(other.request_queue_), upgrading_(other.upgrading_) {}
      // 手动实现拷贝赋值
      LockRequestQueue& operator=(const LockRequestQueue& other) {
          if (this != &other) {
              request_queue_ = other.request_queue_;
              upgrading_ = other.upgrading_;
              // cv_不需要赋值,保持自身的实例即可
          }
          return *this;
      }
      std::list<LockRequest> request_queue_;
      std::condition_variable cv_;
      bool upgrading_ = false;
    };
    
    实现后原main函数的代码即可正常运行。
  • 方案3:用智能指针包裹条件变量成员,让类支持移动
    如果你的业务不需要拷贝对象,只需要转移对象所有权,可以把条件变量用unique_ptr包裹,让类获得默认的移动能力:
    class LockRequestQueue {
     public:
      LockRequestQueue() : cv_(std::make_unique<std::condition_variable>()) {}
      std::list<LockRequest> request_queue_;
      std::unique_ptr<std::condition_variable> cv_;
      bool upgrading_ = false;
    };
    
    int main(){
        LockRequestQueue request;
        std::vector<LockRequestQueue> vecs;
        vecs.push_back(std::move(request)); // 调用移动构造,不会报错
        return 0;
    }
    

内容的提问来源于stack exchange,提问作者xinger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:39:02