面向对象自杀或删除此;
下面用MSVC9.0编译的代码运行并输出Destructor四次,这是符合逻辑的。
#include <iostream>
class SomeClass
{
public:
void CommitSuicide()
{
delete this;
}
void Reincarnate()
{
this->~SomeClass();
new (this) SomeClass;
}
~SomeClass()
{
std::cout << "Destructor\n";
}
};
int main()
{
SomeClass* p = new SomeClass;
p->CommitSuicide();
p = new SomeClass;
p->Reincarnate();
p->~SomeClass(); //line 5
p->CommitSuicide();
}
我认为 main 中的前 4 行代码不会导致未定义的行为(尽管不完全确定 delete this;
事情)。我想要确认或<确认反义词 > 的占位符。但我对第5行和第6行有严重的疑问。允许显式调用析构函数,不是吗?但是在此之后对象的生命周期是否就被认为结束了呢?也就是说,在显式调用析构函数之后是否允许(定义)调用另一个成员?
总而言之,上述代码的哪些部分(如果有)会导致未定义的行为(从技术上讲)?
The following code compiled with MSVC9.0 runs and outputs Destructor four times, which is logical.
#include <iostream>
class SomeClass
{
public:
void CommitSuicide()
{
delete this;
}
void Reincarnate()
{
this->~SomeClass();
new (this) SomeClass;
}
~SomeClass()
{
std::cout << "Destructor\n";
}
};
int main()
{
SomeClass* p = new SomeClass;
p->CommitSuicide();
p = new SomeClass;
p->Reincarnate();
p->~SomeClass(); //line 5
p->CommitSuicide();
}
I think the first 4 lines of code in main do not result in undefined behavior (although not entirely sure about the delete this;
thing). I would like to have a confirmation or < placeholder for confirmation's antonym > of that. But I have serious doubts about lines 5 and 6. It is allowed to explicitly call the destructor, isn't it? But is the lifetime of the object considered to have finished after that? That is, is invocation of another member after the explicit call of the destructor allowed (defined)?
To summarize, which parts of the above code (if any) result in undefined behavior (technically speaking)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
delete this;
就可以了。最后一个p->CommitSuicide();
给出了未定义的行为,因为您已经在“第 5 行”中销毁了该对象。The
delete this;
is fine. The lastp->CommitSuicide();
gives undefined behavior because you already destroyed the object in "line 5".第 (6) 行肯定会调用未定义行为。
不!你的假设是正确的。
Line (6) definitely invokes Undefined Behaviour.
No! Your assumption is correct.
只要您在删除后不尝试调用该对象的任何代码(甚至是析构函数),“删除这个”就可以。因此,自删除对象只能放置在堆上,并且应该有一个私有析构函数来防止在堆栈上创建。
我不知道直接调用析构函数是否会导致未定义的行为,但用户定义的删除运算符不会被执行。
"delete this" is ok as long as you do not attempt to call any code of that object after the deletion (not even the destructor). So a self deleting object shoud only be placed at the heap and shoud have a private destructor to protect from creation on the stack.
I dont know if a direct call to the destructor leads to undefined behaviour but a userdefined delete-operator would'nt get executed.