【发布时间】:2011-04-19 10:10:00
【问题描述】:
我对 C++ 的内部运作有一些疑问。例如,我知道一个类的每个成员函数都有一个隐含的隐藏参数,即 this 指针(与 Python 的做法非常相似):
class Foo
{
Foo(const Foo& other);
};
// ... is actually...
class Foo
{
Foo(Foo* this, const Foo& other);
};
然后假设函数的有效性不直接取决于 this 的有效性(因为它只是另一个参数),我有错吗?我的意思是,当然,如果您尝试访问 this 指针的成员,它最好是有效的,但如果 this 被删除,该函数将继续运行,对吧?
例如,如果我弄乱了 this 指针并执行如下所示的操作怎么办?这是未定义的行为,还是由高度气馁定义的? (我只是出于好奇而问。)
Foo:Foo(const Foo& other)
{
delete this;
this = &other;
}
【问题讨论】:
标签: c++ this this-pointer