由於刪除所有Bar
期從一個Foo
應該刪除Foo
,它可能確實聽起來像是你需要的shared_ptr
期從Bar
秒的極少數的Foo
。
然而,該模型將置於其Bar
S的手Foo
的生命週期:你將無法直接刪除Foo
,而是你必須追捕所有Bar
S和刪除這些。
Foo
將保持Bar*
s,而不是unique_ptr<Bar>
S,因爲它不能前的Bar
小號死亡。但你必須給Bar
S的所有權有人 ...
你可能會與另一個對象最終持有的unique_ptr<Bar>
及其對應於每個Foo
S的集合,但你必須要保持所有這一切同步,因爲Bar
來來去去。這是你試圖避免的同一種記賬方式,但是結果會更大,更復雜和更脆弱,因爲內存泄漏和流氓指針會成爲失敗案例。
所以不是所有這一切,我建議你堅持你的第一unique_ptr
-Powered想法。在實施中的第一步可能看起來像這樣:
struct Foo {
private:
friend void remove(std::unique_ptr<Foo> &foo, Bar const *bar);
// Removes the bar from this Foo.
// Returns true iff the Foo is now empty and should be deleted.
bool remove(Bar const *bar) {
auto i = std::find_if(begin(_bars), end(_bars), [&](auto const &p) {
return p.get() == bar;
});
assert(i != end(_bars));
_bars.erase(i);
return _bars.empty();
}
std::vector<std::unique_ptr<Bar>> _bars;
};
// Removes the bar from the Foo.
// Deletes the Foo if it becomes empty.
void remove(std::unique_ptr<Foo> &foo, Bar const *bar) {
if(foo->remove(bar))
foo.reset();
}
誰擁有'Foo'收藏?這可能是刪除Foos應該去的地方。 – drRobertz
你應該通過代碼強制這個條件,這是非常具體的,我懷疑你會找到一個「優雅」的慣用方法。只是設計一個音響系統 – Dredok
@亞倫Tausky:請看看我的文章,並將其標記爲您的問題的確切答案! – Roland