![](/img/trans.png)
[英]Serializing struct containing vector of pointers with each pointer containing other pointers
[英]How to free a pointer to a vector storing pointers to a struct
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-> 列表?
會是 n->list->clear() 嗎? 或者我是否必須遍歷 n->list 並在列表中的每個元素上調用 delete 或 free 運算符。
std::vector
不承擔動態創建的對象的所有權。
(即使它想要,或者您創建了專門化或您自己的實現,也不可能將動態分配與其他指針區分開來。)
您需要遍歷向量並釋放元素。
更安全/更簡單的是
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>());
}
首先:你不需要那么多指針。
如果你希望它是這樣,你應該像你' new
'它一樣delete
它:)。
在你的例子中:
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;
}
它會導致在刪除node
對象時自動刪除list
。
這一行: struct node * n = new struct node;
也可以轉換為: node n;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.