Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

c++ - shared_ptr::bool SEGSEV

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...