在编写一些树形代码时,我犯了一个错误,在这个例子中,我将其简化为线性树。在main()函数中,我想将一个节点附加到我的树上,但是我不小心将其附加到了“root”而不是“tree.root”。然而,令人惊讶的是,它仍能够正常编译,而且我甚至可以调用节点上的方法。只有在访问"value"成员变量时才会出错。
我想知道的主要问题是为什么编译器没有捕捉到这个bug?
std::shared_ptr<Node> root = tree.AddLeaf(12, root);
由于右边的“root”是一个明显未声明的变量。另外,出于好奇,如果编译器允许它们通过,循环定义是否有实际用途?以下是代码的其余部分:
#include <iostream>
#include <memory>
struct Node
{
int value;
std::shared_ptr<Node> child;
Node(int value)
: value {value}, child {nullptr} {}
int SubtreeDepth()
{
int current_depth = 1;
if(child != nullptr) return current_depth + child->SubtreeDepth();
return current_depth;
}
};
struct Tree
{
std::shared_ptr<Node> root;
std::shared_ptr<Node> AddLeaf(int value, std::shared_ptr<Node>& ptr)
{
if(ptr == nullptr)
{
ptr = std::move(std::make_shared<Node>(value));
return ptr;
}
else
{
std::shared_ptr<Node> newLeaf = std::make_shared<Node>(value);
ptr->child = std::move(newLeaf);
return ptr->child;
}
}
};
int main(int argc, char * argv[])
{
Tree tree;
std::shared_ptr<Node> root = tree.AddLeaf(12, root);
std::shared_ptr<Node> child = tree.AddLeaf(16, root);
std::cout << "root->SubtreeDepth() = " << root->SubtreeDepth() << std::endl;
std::cout << "child->SubtreeDepth() = " << child->SubtreeDepth() << std::endl;
return 0;
}
输出:
root->SubtreeDepth() = 2
child->SubtreeDepth() = 1
int x = x + 1;
这段代码有什么问题?你原本期望它会发生什么? - KamilCuk