Veg*_*eta -5 c++ pointers destructor delete-operator
请检查下面foo函数的析构函数.如果我删除p指针然后运行正常.但如果我在主程序中执行相同操作,那么我会收到错误.为什么它允许我在析构函数中执行此操作?
PS我知道删除指针没有意义,因为没有动态分配的内存.
class foo
{
int* p;
public:
~foo()
{
delete p; // runs fine
cout << "Destructor run \n";
}
};
int main()
{
int* p;
delete p; // This will cause error "uninitialized local variable 'p' used "
foo test; // destructor runs fine at the end of the program
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,有问题的指针都包含一个不确定的值.访问该值,即使只是读取它(更不用说传递给它delete),会导致未定义的行为.当它是一个局部变量时它不行,当它是一个类成员时它也不行.它恰好发生在编译器足够聪明以便在局部变量的情况下捕获它.对于类成员,编译器很难弄清楚程序中的任何内容都不能给指针一个确定的值.