向boost::bimap插入unique_ptr触发拷贝构造函数删除错误求助
问题分析与解决
错误原因
boost::bimap的默认插入逻辑在部分版本中未正确支持C++11移动语义:
- 即便通过
std::move转移std::unique_ptr的所有权,bimap::insert仍会尝试拷贝整个键值对(std::pair<int, std::unique_ptr<student>>) std::unique_ptr的拷贝构造函数是被隐式删除的,因此触发编译错误;错误信息中提到的const std::unique_ptr,是因为bimap内部存储结构中部分元素会被标记为const,进一步触发拷贝操作
解决方案
方案1:使用emplace直接构造元素
通过emplace接口直接在bimap内部构造键值对,避免额外的移动或拷贝操作:
#include <utility> #include <boost/bimap.hpp> class student { int a; public: explicit student(int a) : a(a) {} student(student &&r) noexcept = default; student &operator=(student &&other) noexcept = default; }; int main() { boost::bimap<int, std::unique_ptr<student>> map; // 直接在容器内构造unique_ptr和键值对 map.emplace(4, std::make_unique<student>(5)); }
方案2:显式构造右值pair插入
如果需要先创建unique_ptr再插入,显式构造右值类型的std::pair,确保bimap调用移动语义的重载:
int main() { boost::bimap<int, std::unique_ptr<student>> map; std::unique_ptr<student> a = std::make_unique<student>(5); // 显式生成右值pair,触发移动插入 map.insert(std::make_pair(4, std::move(a))); }
方案3:升级Boost版本
若使用的是较旧的Boost版本(低于1.56),建议升级到支持C++11移动语义的版本,新版本的boost::bimap已完善对右值插入的支持。
内容的提问来源于stack exchange,提问作者Tharani B
相关产品推荐
相关产品推荐

