#include <iostream>
int main()
{
int* aPtr = nullptr;
{
int a = 3;
aPtr = &a;
}
std::cout << *aPtr << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产量
3
Run Code Online (Sandbox Code Playgroud)
我能够获得a通过aPtr.
a即使超出范围也不会被解除分配.a只有在定义它的函数展开后才会释放. #include <iostream>
struct Box
{
Box(int a_)
:a(a_)
{}
int getValue() const { return a;}
~Box()
{
std::cout << "Destructor called" << std::endl;
}
private:
int a;
};
int main()
{
Box* boxPtr = nullptr;
{
Box box = 23;
boxPtr = &box;
}
std::cout << boxPtr->getValue() << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产量
Destructor called
23
Run Code Online (Sandbox Code Playgroud)
我能够获得box通过boxPtr甚至析构函数之后box被调用.
正如评论中提到的,在这两种情况下,您都面临着未定义的行为(因此任何事情都可以发生)。堆栈变量一旦超出范围就会被销毁,它们占用的内存被释放,尽管通常它不会立即被覆盖(至少在上面这样的简单情况下),因此指向此类变量的指针有时可能会表现出更多或更少的“有效”属性(因为它看起来对象仍然有效),尽管它明显悬空。
| 归档时间: |
|
| 查看次数: |
330 次 |
| 最近记录: |