为什么根指针总是初始化为null

Why does the root pointer get initialized to null always?

本文关键字:初始化 null 指针 为什么      更新时间:2023-10-16

我对以下代码感到非常困惑:

class Tree {
protected:
    struct Node {
        Node* leftSibling;
        Node* rightSibling;
        int value;
    };  
private:
    Node* root;
    int value;
.....
public:
    void addElement(int number) {
        if (root == NULL) {
            printf("This is the value of the pointer %lldn",(long long)root);
            printf("This is the value of the int %dn",value);
            ...
            return;
        }
        printf("NOT NULLn");
    }
};

int main() {
    Tree curTree;
    srand(time(0));
    for(int i = 0;i < 40; ++i) {
        curTree.addElement(rand() % 1000);
    }
}

curTree变量是主函数的局部变量,所以我希望它的成员不会初始化为0,但它们都初始化了。

否,它有未指定的内容。这些内容可能是随机内存垃圾,也可能恰好是0,这取决于之前留在其内存位置的数据。

可能只是由于代码的编译方式,包含root的特定堆栈位置总是为0(例如,因为占用相同堆栈位置的早期局部变量最终总是为0)。但你不能依赖这种行为——在读回之前,你必须正确地初始化任何东西,否则你就进入了未定义行为的领域。

指针隐式初始化的实际默认值将取决于您使用的编译器。Visual C编译器(v2012)将自动将其初始化为等于NULL的__nullptr。请查看MSDN文档(请参阅最后一个示例)。

如果你想了解更多信息,我会查看你的编译器手册。

您不会在任何地方初始化root,初始化它的合适位置应该是构造函数。