gra*_*olf 1 c++ visual-c++ c++11
在visual studio中,您可以在已删除的对象上调用函数:
class Foo {
void bar() {
...
}
};
Run Code Online (Sandbox Code Playgroud)
你可以实际执行以下代码而不会出错:
Foo * foo = new Foo();
delete foo;
foo->bar();
Run Code Online (Sandbox Code Playgroud)
并且只要Foo :: bar中的代码不对this
指针执行任何操作.我的第一个问题是,这种未定义的行为是否恰好起作用还是符合标准?
第二个问题:
如果我们将代码更改为:
Foo * foo = new Foo();
delete foo;
foo = nullptr;
foo->bar();
Run Code Online (Sandbox Code Playgroud)
我们可以在Foo :: bar中使用以下检查
if (this == nullptr) {
...
}
Run Code Online (Sandbox Code Playgroud)
以确定我们是否对有效对象进行操作.虽然这样做似乎不太好主意,但是有没有任何架构/设计可能有用?
归档时间: |
|
查看次数: |
211 次 |
最近记录: |