【问题标题】:c++ vector of queues destruction [closed]队列破坏的c ++向量[关闭]
【发布时间】:2015-02-01 18:30:55
【问题描述】:

我正在尝试这样做来破坏Products

vector < queue <Product*> > freshDeposit = ...;
for(queue<Product*> q : freshDeposit){
    for (Product p : q) {
        delete p;
    }
}

但这不起作用!你能帮助我吗? 谢谢!!

【问题讨论】:

  • ProductProduct* 的类型不同。
  • 您不能删除 Product p,因为它不是指针。
  • 哎呀!对这些类型的问题进行投票的速度有多快......即使它们是有效的。
  • 您可能希望queue&lt;Product*&gt; &amp;q : freshDeposit(注意&amp;)避免无用的副本。

标签: c++ c++11 vector destructor


【解决方案1】:

如果可用,您应该几乎总是更喜欢智能指针而不是原始指针。

vector<queue<unique_ptr<Product>>> freshDeposit = ...;
freshDeposit.clear();

或者如果你想保留空队列,

for(queue<unique_ptr<Product>> &q : freshDeposit) {
    q.clear();
}

如果你真的,真的,想要保持数据结构不变,只是释放Product对象,那么你必须使用deque而不是queue并在指针上调用reset()

vector<deque<unique_ptr<Product>>> freshDeposit = ...;
for(deque<unique_ptr<Product>> &q : freshDeposit) {
    for(unique_ptr<Product> &p : q) {
        p.reset();
    }
}

【讨论】:

    猜你喜欢
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2011-12-13
    相关资源
    最近更新 更多