3

インスタンスのセットで範囲ベースの反復子を使用しようとしてい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++;
    }
}

なぜこれが問題になるのか、それを解決する方法はありますか?

4

1 に答える 1

9
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それはイテレータではなく、実際の要素であるため、適切な名前はありません)

于 2014-05-10T17:08:38.720 に答える