C++ 范围 for 循环误拷贝 unique_ptr 导致调用已删除函数如何修复
结论
valid.reset() 本身没有问题。报错来自范围 for 循环中的 auto valid:它按值接收元素,而容器元素类型是 std::unique_ptr<...>。std::unique_ptr 只能移动,不能拷贝;按值遍历会尝试调用已删除的拷贝构造函数。把循环变量改成非 const 引用即可:
for (auto& valid : field->GetFieldProperties().m_validations.m_validators[type]) {
valid.reset();
}
为什么会报错
范围 for 循环会从迭代器取出元素,再用它初始化循环变量。写成 auto valid 时,效果类似 auto valid = *it;,会从一个 unique_ptr 左值复制构造新的 unique_ptr。但 std::unique_ptr 明确禁用了拷贝构造:
unique_ptr(const unique_ptr&) = delete;
因此编译器会报 use of deleted function。后面的 static assertion failed: result type must be constructible from input type 通常也来自同一类问题:某处仍然想从 const unique_ptr& 构造 unique_ptr,常见原因是按值遍历,或者按值拷贝了包含 unique_ptr 的 std::vector。
修复方式
用引用遍历,不复制 unique_ptr
如果 field->GetFieldProperties() 返回的是可用的左值或引用,并且需要调用非 const 的 reset(),循环变量就用非 const 引用:
for (auto& valid : field->GetFieldProperties().m_validations.m_validators[type]) {
valid.reset();
}
这里 auto& 推导出的 valid 是 std::unique_ptr<...>&,不会复制 unique_ptr,也能调用 reset()。不要用 const auto&,因为 reset() 会修改 unique_ptr 本身,const 引用无法调用。
GetFieldProperties() 按值返回时,先保存返回值
如果 GetFieldProperties() 返回的是临时对象,先把属性保存到局部变量,再遍历它的成员容器。这样可以避开临时对象生命周期和成员访问的问题,代码也更清楚:
auto&& props = field->GetFieldProperties();
for (auto& valid : props.m_validations.m_validators[type]) {
valid.reset();
}
如果返回类型可以复制,而且你确实需要一份副本,也可以使用值变量:
auto props = field->GetFieldProperties();
for (auto& valid : props.m_validations.m_validators[type]) {
valid.reset();
}
但要注意,如果 GetFieldProperties() 返回的对象里包含 std::vector<std::unique_ptr<...>>,按值复制整个对象本身就可能无法编译,因为 unique_ptr 不能拷贝。这时应使用引用或移动语义,而不是复制。
只读访问时
如果只是想检查元素,不修改它,可以用 const 引用,但不要调用 reset():
for (const auto& valid : props.m_validations.m_validators[type]) {
// 只读访问 valid
}
注意事项
auto valid会复制元素。遇到unique_ptr、std::vector<std::unique_ptr<T>>这类只能移动的类型,循环变量优先用auto&或auto&&。reset()会释放unique_ptr当前持有的对象,并把指针置空。只读时不要调用。- 容器或属性对象是 const 时,不能对元素调用非 const 的
reset()。 - 修改后如果仍然出现
static assertion failed,继续检查有没有按值返回、按值传参,或者按值遍历了包含unique_ptr的容器。
备注:内容仅供参考。
