存储unique_ptrs,shared_ptrs或ID的列表?

时间:2016-03-15 18:51:47

标签: c++ c++11

我们说我的课程看起来像这样:

class Foo
{
public:
    Foo();
private:
    int id;
    //Other data...
    std::list< ??? > connected_foo;
}

class Bar
{
public:
    Bar();
private:
    std::list<std::unique_ptr<Foo> > all_foo;
}

在课程Foo中,我创建了一个类似图形的结构,以便某些Foo个对象链接到其他Foo个对象。

在C ++ 11中,大多数&#34;正确&#34;?具体来说,???应该是什么? unique_ptr列表? shared_ptr列表?或者是int的列表,其中包含迭代all_foo并查找特定对象的函数?

或者我应该一起使用不同的数据结构(即map)?我知道Boost库提供了图形,但这比我在这里寻找的要多一些(a.k.a。希望坚持使用C ++标准库)。

如果&#34;正确&#34;太模糊(可能是),假设优先级是可读性,最不可能导致内存泄漏,以及简洁,按顺序。

一些注意事项:我对C ++(来自C)相当新,所以我试图不使用C ++作为&#34; C与OO&#34;。在C中,我使用一个指针数组并且最有可能在一天中调用它(特别是因为我知道在程序结束之前对象不会被释放);无法创建unique_ptr的副本让我有点沮丧。我在此瞄准的具体应用是从逻辑门(使用OO)创建电路。这是一个(毕业)学校项目。

2 个答案:

答案 0 :(得分:1)

在不知道完整用例的情况下,可能无法给出答案。但是,如果Bar确实拥有所有Foo并且将比所有std::vector<Foo*> connected_foo; 更长(正如您在问题中所述),我建议:

unique_ptr<Foo>

原始指针没有错 - 我们没有使用它们来传达任何所有权语义,只是观察。

容器Bar错误 - shared_ptr<Foo>已拥有唯一所有权。您可以将它们设为Bar(并更改Bar以共享所有权)。这是正确的,但如果 public class AccountLimit { private readonly IMoneyService _moneyService; private readonly ILimitService _limitService; private readonly long _customerId; public AccountLimit(long customerId,IMoneyService moneyService,ILimitService limitService) { _moneyService = moneyService; _limitService = limitService; _customerId = customerId; } private decimal withdrawalSum { get { return _moneyService.GetTotalWithdrawal(_customerId); } } private decimal depositSum { get { return _moneyService.GetTotalDeposit(_customerId); } } private decimal depositLimit { get { return _limitService.GetDeposlitLimit(_customerId); } } private decimal withDrawalLimit { get { return _limitService.GetwithdrawalLimit(_customerId); } } public decimal RemainingDeposit{ get { return depositLimit - depositSum; } } public decimal RemainingWithdrawal { get { return withdrawalLimit - withdrawalSum; } } } 确实拥有它们,那就没必要了。相反,存储ID意味着进行查找会更加昂贵,所以我不确定这会带来什么好处。

答案 1 :(得分:0)

如果您不打算遍历all_foo并在每次删除对象时清除所有对象中的引用,那么您可以使用std::list<std:weak_ptr<Foo>> connected_foo;并按需检查并更新connected_foo。然后,当您想在节点中使用连接的foo时,首先将其锁定为共享并检查它是否存在,如果不存在,则将其从连接列表中删除。请注意,您必须将std::list<std::shared_ptr<Foo>>保留在all_foo中。