我正在尝试实现一个SegmentTree类以在另一个类中使用Solution。
在 中class SegmentTree,析构函数的实现如下:
~SegmentTree() {
destruct(root);
};
void destruct(Node* root) {
if (!root) return;
destruct(root->left);
destruct(root->right);
delete root;
root = NULL;
}
Run Code Online (Sandbox Code Playgroud)
那么,在 中class Solution,我们有
class Solution {
private:
SegmentTree* tree;
public:
Solution(vector<int>& nums) {
tree = new SegmentTree(nums);
}
//Question: how shall ~Solution() be implemented to free memory of the pointer tree?
};
Run Code Online (Sandbox Code Playgroud)
问题:
tree中的指针Solution?我们是否需要实现析构函数来删除类
tree中的指针Solution?
如果您使用创建对象,则在使用完该对象后new需要该对象。delete所以是的,Solution需要一个它的析构delete函数(就像需要一个它的析构函数一样)。treenewSegmentTreedeleteNodenew
如果是,该如何实施?
像这样:
class Solution {
private:
SegmentTree* tree;
public:
Solution(vector<int>& nums) :
tree(new SegmentTree(nums))
{
}
~Solution() {
delete tree;
}
};
Run Code Online (Sandbox Code Playgroud)
您可以使用自动化操作std::unique_ptr,例如:
class Solution {
private:
std::unique_ptr<SegmentTree> tree;
public:
Solution(vector<int>& nums) :
tree(std::make_unique<SegmentTree>(nums))
//tree(new SegmentTree(nums))
{
}
};
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,请注意3 规则:
如果一个类需要用户定义的析构函数、用户定义的复制构造函数或用户定义的复制赋值运算符,那么它几乎肯定需要这三个函数。
因此,您还应该实现(或禁用)复制构造函数和复制赋值运算符,例如:
class Solution {
private:
SegmentTree* tree;
public:
Solution(vector<int>& nums) :
tree(new SegmentTree(nums))
{
}
Solution(const Solution &src) :
tree(new SegmentTree(*(src.tree)))
{
}
~Solution() {
delete tree;
}
Solution& operator=(const Solution &rhs) {
if (&rhs != this) {
Solution tmp(rhs);
std::swap(tree, tmp.tree);
}
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
new不过,您可能会考虑一开始就简单地摆脱它,让编译器SegmentTree为您管理对象:
class Solution {
private:
SegmentTree tree;
public:
Solution(vector<int>& nums) :
tree(nums)
{
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
757 次 |
| 最近记录: |