I'm trying to implement a SegmentTree
with smart pointers. For that I use a TreeNode
class, which stores shared pointers to its children and a weak pointer to its ancestor.
The left_son
and right_son
pointers are initialized with nullptr
:
template<typename T, T(*Union)(T, T)>
class SegmentTree {
class TreeNode {
T data;
std::shared_ptr<TreeNode> left_son = nullptr;
std::shared_ptr<TreeNode> right_son = nullptr;
std::weak_ptr<TreeNode> ancestor;
The TreeNode
class has a function that initializes its children:
void CreateChildren() {
if (l == r) {
return;
}
int mid = (l + r) / 2;
if (!left_son) {
left_son.reset(new TreeNode(std::shared_ptr<TreeNode>(this), l, mid));
}
if (!right_son) {
right_son.reset(new TreeNode(std::shared_ptr<TreeNode>(this), mid + 1, r));
}
}
The constructor used in new TreeNode
takes in a shared pointer to the ancestor and a segment, that the new node corresponds to.
Somewhy, when I debug the program with gdb, if step in the if (!right_son)
comand, it crashes there, but if I just step over, the comand just returns false and the program crushes later, because the right_son
pointer is pointing to nullptr
and wasn't initialized there.
So what is going on? I am totally confused. If right_son
is initialized with nullptr
, then why (bool)right_son
returns true?
question from:
https://stackoverflow.com/questions/66055149/shared-ptrbool-segsev 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…