2016-02-08 34 views
0

我是來自boost的shared_ptr的新手,並且正在考慮迭代我的集合以獲取最佳對象。 編輯:關於first_world添加信息循環迭代後共享指針斷言失敗

std::set<World::CPtr> first_world = ... // long call, but it gets a set of constant shared pointers to the class World, where various methods exist 

    typedef boost::shared_ptr<World const> CPtr; 
    World::CPtr best = *(first_world.begin()); 
    for (World::CPtr lo : first_world) { 
    if (best->getValue() >= lo->getValue()){ 
     best = lo; 
    } 
    } 

後來我想使用共享指針,我的程序與傳達斷言`PX崩潰= 0' 失敗!我遵循here的規則,我的意思是我在循環中使用了一個共享指針作爲迭代器,但隨後我將它分配給另一個指針。那是不好的做法,有沒有更好的做法?

cout << "name is: " << best->getDefinition() << endl; 
+0

爲什麼在明顯使用C++ 11時使用'boost :: shared_ptr'? – molbdnilo

+0

@molbdnilo爲什麼不呢?似乎相當無關緊要。上次我檢查的類型是不一樣的,並且使用你的代碼庫需要的類型是有意義的... – sehe

+0

well C++ 11沒有必要,我會將其更改爲舊標準 - 我想了解的是爲什麼這不起作用,如何使其工作。 – beginh

回答

0

什麼東西粘貼在那裏沒有明顯的錯誤,所以可能會在創建該設置的長時間調用中出現錯誤。

例如,如果在將元素添加到集合時涉及原始指針,則很容易搞砸了。考慮這種情況,這是那種提到在您的最佳實踐的一個常見錯誤的具體說明鏈接:

std::set<World::CPtr> first_world; 

World* pWorld = new World(); 

// Bad: 
first_world.insert(World::CPtr(pWorld)); 
first_world.insert(World::CPtr(pWorld)); 

// Oops!! You now have two independently refcounted entries in first_world! 

// emplace is just as deadly, but more subtle. 
// Now you'll have three shared pointers in your set: 
first_world.emplace(pWorld); 

如果您通過條目first_world看看,看看重複的,那麼你就會知道,你就麻煩了。爲了避免這樣的錯誤,請確保只構造來自其他shared_ptrs的shared_ptrs(或boost::make_shared)。

這就是提示#1:避免從原始指針構建shared_ptrs。 (其中包括this指針,如果世界將自己添加到您的設置...如果你這樣做,更好地開始搜索enable_shared_from_this)。

現在,讓我們遵循這條金科玉律得到預期的行爲:

std::set<World::CPtr> first_world; 

World::CPtr spWorld1 = boost::make_shared<World>(); 
World::CPtr spWorld2{spWorld1}; 

first_world.insert(spWorld1); 
first_world.insert(spWorld2); 
// Just one element in first_world now, as expected. 

最後,幾個(有點不相關的)建議:

  • std::set因爲你已經聲明它只是在看地址當它比較條目時堆上的世界對象。所以如果你在堆上有兩個不同的世界在邏輯上是相同的,那麼它們在這個集合中將有不同的條目。這是你的意圖嗎?如果你想避免邏輯重複,你需要插入你自己的自定義比較函數(std :: set的第二個模板參數)來深度比較Worlds。
  • 檢查以確保first_world在查找最大值之前不爲空,否則會發生不好的事情。
  • 標準算法是你的朋友!考慮使用std::max_element算法而不是原始循環。 (這使得其他人更容易通過快速瀏覽來推斷你正在做什麼)。