C++,在基类上调用删除会导致
C++, Calling delete on Base Class results in?
我有两个与以下代码相关的问题C++:
class Base
{
public:
virtual bool deleteMe()
{
delete this;
return true;
}
};
class Derived: public Base
{
public:
void setBCO(const BigCustomObject& t_BCO)
{ m_BCO=t_BCO;}
BigCustomObject m_BCO;
};
int main()
{
Derived *pDerived = new Derived();
//insertint the "BigCustomObject" by new or local copy makes no difference, or?
//Because the "setBCO(){m_BCO=t_BCO;}" calls the copy operator anyway, or?
pDerived->setBCO( ... );
bool checkDel = pDerived->deleteMe();
//bool checkDel = ((Base*)pDerived)->deleteMe(); //Does this make any difference?
std::cout<<checkDel;
}
1.) deleteMe() 函数在删除自己的对象后怎么可能返回一个值???
2.) 当仅删除基本对象时,派生对象中的"BigCustomObject"会发生什么情况?
谢谢。
-
为其执行代码的对象仅用作
this
指针(以及非限定成员名称的隐式容器)。它与可执行代码本身没有任何关系,因此可以正常继续执行。但是,如果deleteMe()
在删除后尝试访问this
的任何数据成员,则会遇到麻烦。 -
在您的情况下,它可能已泄露。从技术上讲,代码具有未定义的行为,因此任何事情都可能发生。原因是
Base
没有虚拟析构函数,因此未定义通过指向基类的指针删除派生对象。但是,如果Base
有一个虚拟析构函数,它将正常工作 -Derived
的析构函数将被调用(通过虚拟调度),而虚拟调度又会调用BigCustomObject
的析构函数来销毁m_BCO
然后调用Base
的析构函数。
1)代码不会仅仅因为对象的内存而自毁。它只是意味着成员变量引用的数据将是无效的。
2)我猜BigCustomObject没有被正确破坏,因为Base没有虚拟析构函数。
首先,基类没有虚拟析构函数,因此当您调用delete this
(这是Base
)时Derived
类中的 BigCustomObject 不会被销毁。此外,函数的执行仍然可以,因为您不再使用对象(this)。
您的问题的答案在示例代码的注释中:
class Base
{
public:
virtual bool deleteMe()
{
this->some_member = 0;//valid
delete this;
//from here on everything you do you can is ok if you don't touch `this`
//for example:
//this->some_member = 0;//this is not safe since the object this is already destroyed
return true;
}
virtual ~Base()
{
//virtual means that Dirived class has it's destructor called before this one does
}
int some_member;//member added to illustrate the lifetimeo of base class
};
相关文章:
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 如何知道何时调用删除以及何时调用 delete[] C++?
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 线程调用的函数对对象删除是否安全?
- 在运行时有条件地删除类成员或跳过调用该成员对象的构造函数
- 调用类模板中隐式删除的复制构造函数
- 编译器在C++中调用另一个函数时,在参数中查找已删除的构造函数
- C++ 在析构函数调用之前删除的动态成员数组
- 为什么为未删除的对象调用析构函数?
- 删除了在初始值设定项中调用的构造函数
- 在调用过程中删除 std::函数
- 防止我的向量在调用它的函数结束时被删除
- 除了调用全局删除运算符之外,删除一个void指针还能做什么呢
- 为什么这不是"调用隐式删除的'QQmlElement'的默认构造函数"中的默认构造函数
- 删除调用析构函数,但不删除对象
- 在 Visual C++ 中删除调用后检测到堆损坏
- 删除[]调用析构函数
- 在回调函数中安全地删除调用方对象
- 重新分配变量,删除调用了两次(C++)