Do we need to implement destructor to delete tree
pointer in Solution
class?
If you use new
to create an object, you need to delete
the object when you are done using it. So yes, Solution
needs a destructor to delete
the tree
that it new
's (just as SegmentTree
needs a destructor to delete
the Node
's that it new
's).
If yes, how shall that be implemented?
Like this:
class Solution {
private:
SegmentTree* tree;
public:
Solution(vector<int>& nums) :
tree(new SegmentTree(nums))
{
}
~Solution() {
delete tree;
}
};
Which you can automate by using std::unique_ptr
, eg:
class Solution {
private:
std::unique_ptr<SegmentTree> tree;
public:
Solution(vector<int>& nums) :
tree(std::make_unique<SegmentTree>(nums))
//tree(new SegmentTree(nums))
{
}
};
Either way, do be aware of the Rule of 3:
If a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three.
So, you should also implement (or disable) the copy constructor and copy-assignment operator, eg:
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;
}
};
Though, you might consider simply getting rid of new
to begin with and just let the compiler manage the SegmentTree
object for you:
class Solution {
private:
SegmentTree tree;
public:
Solution(vector<int>& nums) :
tree(nums)
{
}
};