【问题标题】:C++11 for loop through vector of unique_ptrC++11 for 循环遍历 unique_ptr 的向量
【发布时间】:2015-07-01 20:44:14
【问题描述】:

在将 unique_ptrs 向量正确循环到我自己的自定义对象时遇到问题。我在下面提供了伪代码,它没有完全充实,但专注于 for 循环。我想使用 C++11“for”循环,并遍历向量 - 或者从我听说的情况来看,提供自己的迭代器更好?当我有单独的课程时,我只是不知道该怎么做。如果我将向量保存在管理器类中,那么我应该在哪里定义迭代器方法?在对象类中,还是在管理器类中?我还想确保我的数据保持不变,因此无法更改实际值。

// Class for our data
Class GeoSourceFile
{
    // some data, doesn't matter
    double m_dNumber;
    int    m_nMyInt;
}
// singleton manager class
Class GsfManager
{
  public:
    // Gets pointer to the vector of pointers for the GeoSourceFile objects
    const std::vector<std::unique_ptr<GeoSourceFile>>* GetFiles( );
  private:
    // Vector of smart pointers to GeoSourceFile objects
    std::vector<std::unique_ptr<GeoSourceFile>> m_vGeoSourceFiles;  
}
void App::OnDrawEvent
{
    GsfManager* pGsfMgr = GsfManager::Instance();
    for(auto const& gsf : *pGsfMgr->GetFiles() )
    {
         oglObj->DrawGeoSourceFile( file );
    }
}

void OglClass::DrawGeoSourceFile( std::unique_ptr<GeoSourceFile> file )
{
    //...
}

【问题讨论】:

    标签: c++11 for-loop iterator stdvector unique-ptr


    【解决方案1】:

    自己找到了我的问题的答案。

    这里要记住的重要一点是,您不能创建 unique_ptr 的副本...这包括将指针传递给其他函数。如果将 unique_ptr 传递给另一个函数,则必须在接收函数中使用 & 字符。

    例如:

    void OglClass::DrawGeoSourceFile( const std::unique_ptr<GeoSourceFile> file )
    {
        // fails to compile, you're getting a copy of the pointer, which is not allowed
    }
    
    void OglClass::DrawGeoSourceFile( const std::unique_ptr<GeoSourceFile>& file );
    {
        // successfully compiles, you're using the original pointer
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-16
      • 2021-06-26
      • 2015-05-21
      • 2012-01-22
      • 2012-09-12
      • 2015-07-24
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      相关资源
      最近更新 更多