【问题标题】:using range-based for with std::set<std::unique_ptr<T>> deleted function对 std::set<std::unique_ptr<T>> 删除函数使用基于范围的 for
【发布时间】:2014-06-28 08:06:07
【问题描述】:

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

知道为什么这会是一个问题或如何解决它吗?

【问题讨论】:

  • std::set&lt;std::unique_ptr&lt;Component&gt;&gt;* - 很可能,set 本身不需要是指针。此外,您使用智能指针保存set 中的元素但决定手动管理set 的内存,这很奇怪。
  • @Praetorian,集合实际上是一个类的成员,在析构函数中创建和销毁类时初始化。我试图创建一个简单的例子来说明我的问题。这似乎是正确的方法,但我有点初学者,所以如果有更好的方法,请告诉我。
  • std::set&lt;std::unique_ptr&lt;Component&gt;&gt; m_components 是更好的方法。它将与您的类实例一起被实例化和销毁,不再需要newdelete
  • 太棒了!谢谢你的提示。我第一次在这里发帖。刚刚创建了一个帐户,并且已经对它的响应速度和资源价值感到惊讶。

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


【解决方案1】:
for (auto componentsIterator : *m_components)

auto 扩展为std::unique_ptr&lt;Component&gt;,这意味着您正在尝试获取每个元素的副本。 IOW,那个循环实际上是:

for(auto it=m_components->begin(); it!=m_components->end(); ++it)
{
    std::unique_ptr<Component> componentsIterator=*it;
    componentsIterator->DoSomething();
    componentsIterator++;
}

如您所见,您正在调用std::unique_ptr&lt;Component&gt; 复制构造函数,但unique_ptr 的复制构造函数被删除(因为它违反了unique_ptr 语义)。

使用auto &amp; 代替引用。

(顺便说一句,componentsIterator 没有一个合理的名称,因为它不是迭代器,而是实际元素)

【讨论】:

  • 感谢您的即时回复。它有帮助,但并没有完全让我到达那里,因为我仍然在增量运算符 C2676 上遇到错误:二进制'++':'const std::unique_ptr>' 没有定义这个运算符或转换为预定义运算符可接受的类型
  • @jhegedus:你打算用那个++做什么? unique_ptr 没有定义任何 ++ 运算符,它是你的 Component 类的东西还是你把它放在那里移动到循环中的下一个元素?
  • 我认为我需要 ++ 来遍历循环。我误会了吗?
  • @jhegedus:是的,你误会了;基于范围的for 已经解决了这个问题。
  • 其实,我明白我误解了,那是在为你扩展为我。再次感谢
猜你喜欢
  • 2016-02-01
  • 2021-10-07
  • 1970-01-01
  • 2022-10-21
  • 2020-12-20
  • 2022-01-07
  • 1970-01-01
  • 2019-11-07
  • 2015-07-23
相关资源
最近更新 更多