c++ - 将基于范围的 for 与 std::set<std::unique_ptr<T>> 删除函数一起使用

标签 c++ c++11 set unique-ptr deleted-functions

我正在尝试将基于范围的迭代器与一组 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/

相关文章:

c++ - 为什么 istream::getline() 返回这么多次(什么都没有)

python - 如何将集合中的条目连接成一个字符串?

c++ - 设置 shared_ptr 并设置函数计数

python - 如何从集合中获取列表?

c++11 - 无法在 std::map 中使用 std::shared_ptr 作为值类型?

使用 MSVC 2013 的 C++11 类内初始化器

c++ - pImpl 习语 - 将私有(private)类实现放在 cpp 中有什么缺点?

c++ - 复制时使用的理想内存块大小是多少?

c++ - std::wstring_convert 线程的成员函数是否安全?

C++ STL unordered_map问题与疑惑