struct node {
std::vector<struct node*> * list;
}
int main() {
struct node * n = new struct node;
n->list = new std::vector<struct node*>();
n->list->push_back(n);
return 0;
}
如何通过释放列表存储的所有指针来删除n-&gt;列表?
是n-&gt; list-&gt; clear()?或者我是否必须遍历n-&gt;列表并在列表中的每个元素上调用delete或free运算符。
答案 0 :(得分:3)
std::vector
不承担动态创建对象的所有权
(即使它想要,或者您创建了专门化或您自己的实现,也无法区分动态分配与其他指针。)
您需要遍历向量并释放元素。
答案 1 :(得分:3)
更安全/更简单的是
struct node {
std::vector<node> list;
};
int main() {
node n;
n.list.resize(1);
}
或者如果你需要指针:
struct node {
std::vector<std::unique_ptr<node>> list;
};
int main() {
node n;
n.list.push_back(std::make_unique<node>());
}
答案 2 :(得分:0)
首先:你不需要这么多指针。
如果您希望这样,那么您应该delete
完全按照new
编辑&#39; int main() {
struct node * n = new struct node;
n->list = new std::vector<struct node*>();
n->list->push_back(n);
delete n->list; // here's the change
delete n; // another required delete
return 0;
}
它:)。
在你的例子中:
new
但正如我所说,node
太多了。
您可以将结构struct node {
std::vector<struct node*> list;
}
编写为:
list
当删除node
对象时,它会导致struct node * n = new struct node;
自动删除。
这一行:node n;
也可以转换为:
<?php
$product = Mage::getModel('catalog/product')->load($_item->getProductId());
echo $product->getAttributeText('meal_time');
?>