【发布时间】:2014-02-28 16:38:57
【问题描述】:
我试图了解在这个简单的情况下破坏是如何工作的:
class A {
public:
A(int i) { this->b = i; }
void p() { std::cout << a << " " << b << std::endl;}
private:
string a = "42";
int b = 0;
};
int main() {
A* ap = nullptr;
while (true) {
A k(24);
ap = &k;
k.p();
break;
} // A out of scope, I expect any pointer to A to be invalidated.
ap->p(); // still callable, b has been freed but not a!?
}
ap 怎么会指向一个部分有效的对象?我做错了什么并且不理解?请准确解释,因为我是 C++ 新手。谢谢!
编辑:假设我在 ~A(); 中调用 p();这样做安全吗?
【问题讨论】:
-
未定义的行为正如其名称所暗示的那样不可预测和不可靠。不要假设观察到的行为是定义的行为。
标签: c++ scope destructor