无法正确地循环遍历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 )
{
//...
}
发布于 2015-07-02 00:27:31
我自己找到了问题的答案。
这里要记住的重要一点是,您不能创建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
}
https://stackoverflow.com/questions/31171317
复制相似问题