gpt4 book ai didi

c++ - 阐明 C++ 结构中数据类型的析构函数要求

转载 作者:行者123 更新时间:2023-12-01 14:38:59 37 4
gpt4 key购买 nike

结构体的析构函数:
您能否指定必须在结构的析构函数中显式处理的每种数据类型?

struct Node {
int val; // representing any/all primitive data types
int* ptrToVal; // representing any/all pointers to primitive data types
int arr[5]; // representing any/all arrays
int* ptrToArr[5]; // representing any/all array of pointers
Node* next; // pointer to a struct
vector<Node> vOfNodes; // vector of structs
vector<Node*> vOfPtrs; // vector of struct pointers
unordered_map<int, Node*> um; //representing any pre-existing class template

// Default constructor
Node() : val(0), ptrToVal(nullptr), arr(), ptrToArr(), next(nullptr),
vOfNodes(), vOfPtrs(), um(){}

//Overloaded constructor
Node(int val, int* toVal, Node* n, vector<Node> vN, vector<Node*> toV,
unordered_map<int, Node*> m)
: val(val), ptrToVal(toVal), arr(), ptrToArr(), next(n),
vOfNodes(vN), vOfPtrs(toV), um(m){}
需要向 Node 结构的析构函数添加什么?是否还有其他我没有想到的棘手数据结构也需要析构函数中的非平凡代码?

最佳答案

任何东西都可能需要显式销毁:int可以是要关闭的文件描述符,数组(对象外部)的索引,标识要以某种方式完成的对象,或存储为 std::uintptr_t 的指针出于类型删除的原因。函数指针可以是要调用的已注册清理函数。具有自己的析构函数的对象可能包含它不知道如何处理的任何这些类型的信息。
另一方面,作为显式销毁的典型子对象的原始对象指针可能只是指向另一个数据结构的非拥有(“观察”)指针,根本不需要清理。
所以没有预先确定的答案:你必须考虑为什么对象有每个成员以及它是什么拥有 关于每个。

关于c++ - 阐明 C++ 结构中数据类型的析构函数要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63123038/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com