PAYATHON 2026

C++ map 中 vector<unique_ptr> 复制导致编译错误

数据小陈

结论

问题出在这一行,和 <vector> 的 include 顺序无关:

auto test = field->GetFieldProperties().m_validations.m_validators[type];

operator[] 返回 std::vector<std::unique_ptr<ValidatorSet>>&。这里用 auto 会把引用去掉,推导成值类型,于是要复制整个 vector。std::vector<std::unique_ptr<T>> 不能复制,因为 std::unique_ptr 只支持移动,不支持复制,编译就失败了。把 auto 改成 auto& 或 const auto& 就能解决。

原因分析

std::map<int, std::vector<std::unique_ptr<ValidatorSet>>> 的 mapped_type 是 std::vector<std::unique_ptr<ValidatorSet>>。m_validators[type] 返回这个 vector 的左值引用。写成 auto test = ... 时,test 的类型被推导为 std::vector<std::unique_ptr<ValidatorSet>>,会调用 vector 的拷贝构造。vector 的拷贝构造要逐个复制元素,也就是从 const std::unique_ptr<ValidatorSet>& 构造 std::unique_ptr<ValidatorSet>。unique_ptr 的拷贝构造已经被删除,所以 std::is_constructible 为 false,最终触发:

static assertion failed: result type must be constructible from input type

错误堆栈里出现 std::map 的复制赋值路径,通常说明包含这个 map 的 FieldProperties 或 FieldTableValidationProperties 在某处被复制或赋值。这个类型默认不可复制。业务上确实需要复制时,得自己实现深拷贝,或者改用可复制的智能指针。

解决步骤

  1. 只是访问或修改已有元素时,用引用接收:
auto& test = field->GetFieldProperties().m_validations.m_validators[type];
  1. 只读访问时用 const 引用:
const auto& test = field->GetFieldProperties().m_validations.m_validators.at(type);

at 在 key 不存在时会抛 std::out_of_range,不会像 operator[] 那样插入一个空 vector。

  1. key 可能不存在,又不想让 operator[] 插入新元素时,可以先 find:
auto& validators = field->GetFieldProperties().m_validations.m_validators;
auto it = validators.find(type);
if (it != validators.end()) {
    auto& test = it->second;
    // 使用 test
}
  1. 确实要复制容器时,不能直接复制 vector<unique_ptr<T>>。可以写显式深拷贝函数,把每个 ValidatorSet 复制后放进新的 unique_ptr;也可以把 std::unique_ptr 改成 std::shared_ptr,前提是共享所有权的语义合理;还可以删除包含该 map 的类的拷贝构造和拷贝赋值,只保留移动语义。

代码示例

下面的示例只改访问方式,数据结构保持不变:

Field *field = nullptr; // 按实际代码初始化
int type = 0;

auto& test = field->GetFieldProperties().m_validations.m_validators[type];
// test 的类型是 std::vector<std::unique_ptr<ValidatorSet>> &

如果后面要遍历元素,也保持引用或指针语义:

for (auto& validatorPtr : test) {
    if (validatorPtr) {
        // 使用 *validatorPtr
    }
}

注意事项

  • std::unique_ptr 不可复制,std::vector<std::unique_ptr<T>> 只能移动,不能拷贝。
  • auto test = ... 和 auto& test = ... 语义完全不同;前者复制,后者绑定引用。
  • operator[] 在 key 不存在时会插入默认构造的 vector;只读或不想插入时优先用 find 或 at。
  • 错误信息指向 <vector> 是模板实例化位置,不代表 include 顺序有问题。
  • 如果包含该 map 的类需要按值传递或复制赋值,请显式实现深拷贝,或把拷贝操作删除并改用移动。

备注:内容仅供参考。