我正在尝试将基于范围的迭代器与一组 unique_ptr
实例一起使用,但出现以下编译错误:
C2280: 'std::unique_ptr<Component,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
代码的基础如下:
#include <set>
#include <memory>
std::set<std::unique_ptr<Component>>* m_components;
class Component
{
void DoSomething(){};
};
void ProcessComponents()
{
for (auto componentsIterator : *m_components)
{
componentsIterator->DoSomething();
componentsIterator++;
}
}
知道为什么这会成为问题或如何解决吗?
最佳答案
for (auto componentsIterator : *m_components)
那个auto
扩展为 std::unique_ptr<Component>
,这意味着您正在尝试获取每个元素的拷贝。 IOW,那个循环实际上是:
for(auto it=m_components->begin(); it!=m_components->end(); ++it)
{
std::unique_ptr<Component> componentsIterator=*it;
componentsIterator->DoSomething();
componentsIterator++;
}
如您所见,您正在调用 std::unique_ptr<Component>
拷贝构造函数,而是unique_ptr
的拷贝构造函数被删除(因为它违反了 unique_ptr
语义)。
使用 auto &
取而代之的是引用。
(顺便说一句,componentsIterator
没有一个合理的名称,因为它不是迭代器,而是实际的元素)
关于c++ - 将基于范围的 for 与 std::set<std::unique_ptr<T>> 删除函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23583992/