I am trying to write a tree data structure with unique_ptr but I ma getting following warning while printing the Tree:
struct Node {
int data_{0};
std::unique_ptr<Node> left_{nullptr};
std::unique_ptr<Node> right_{nullptr};
};
void print(Node &root) {
if (&root == nullptr) return;
print(*root.left_);
std::cout << root.data_ << " ";
print(*root.right_);
}
I get following warning from compiler:
Reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to always evaluate to false. In print(...) function.
How to fix this warning?
I want solve this using unique_ptr.
You test if the address of root
is equal to nullptr
. The address of a reference variable can not be nullptr
.
void print(Node &root) {
if (&root == nullptr) return; // will never be true
What you probably want is to check if the unique_ptr
s are not empty before dereferencing them:
void print(const Node& root) {
if (root.left_) print(*root.left_); // check added
std::cout << root.data_ << ' ';
if (root.right_) print(*root.right_); // check added
}
Alternatively, use pointers:
void print(const Node* root) {
if(root == nullptr) return; // now this check makes sense
print(root->left_.get());
std::cout << root->data_ << ' ';
print(root->right_.get());
}
...or pass a reference to the unique_ptr
directly:
void print(const std::unique_ptr<Node>& root) {
if (root == nullptr) return;
print(root->left_);
std::cout << root->data_ << ' ';
print(root->right_);
}