use*_*248 3 c++ variable-initialization
我对以下代码非常困惑:
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 %lld\n",(long long)root);
printf("This is the value of the int %d\n",value);
...
return;
}
printf("NOT NULL\n");
}
};
int main() {
Tree curTree;
srand(time(0));
for(int i = 0;i < 40; ++i) {
curTree.addElement(rand() % 1000);
}
}
Run Code Online (Sandbox Code Playgroud)
该curTree变量是main函数的本地变量,因此我预计它不会将其成员初始化为0,但它们都已初始化.
Ada*_*eld 12
不,它有未指定的内容.这些内容可能是随机内存垃圾,或者它们恰好可能是0,这取决于事先在其内存位置留下的数据.
可能恰好由于编译代码的方式,包含的特定堆栈位置root始终为0(例如,因为占用相同堆栈位置的早期局部变量总是最终为0).但是你不能依赖这种行为 - 你必须在读回之前正确地初始化任何东西,否则你进入了未定义行为之地.