尝试删除指向派生对象的基指针时断言错误
Assertion error attempting to delete base pointer to derived object
在C++研究继承时,我了解到用于多态行为的基类应该将其析构函数实现为virtual
我以为我知道如何很好地应用它,但我遇到了一个我不明白的小问题。
给定以下代码:
#include <iostream>
struct Base
{
Base() { std::cout << "Base ctor calledn"; };
virtual ~Base() { std::cout << "Base dtor calledn"; };
};
struct Derived : Base
{
Derived() : Base() { std::cout << "Derived ctor calledn"; }
~Derived() { std::cout << "Derived dtor calledn"; };
};
int main()
{
Derived d;
Base *p_base = &d;
delete p_base; //Problem here?
return 0;
}
输出符合预期:
Base ctor called
Derived ctor called
Derived dtor called
Base dtor called
但是,发生_CrtisValidHeapPointer(block)
断言错误。
如果p_base
直接指向一个新的Derived
对象,一切正常,即Base *p_base = new Derived();
这里有什么不同?
亲切问候
问题是本地构造的对象d
将在其作用域结束时自动删除,在您调用return 0
的情况下。但是当时,您已经删除了指向同一对象的p_base
。因此,该对象将被删除两次。
您的问题与继承无关。即使同一类的对象也应该出现。
相关文章:
- 访问提升:shared_ptr 主范围外崩溃,断言失败:px != 0.指针的正确用法是什么?
- 尝试删除指向派生对象的基指针时断言错误
- C++ 调试断言失败,无效的空指针
- C++ 调试断言失败指针
- 删除SDL_VideoInfo指针时调试断言失败
- 在delete()之后不会断言两个指针都指向NULL
- 将派生类对象分配给基类对象时会发生什么(我的意思是对象断言,而不是指针)
- 正在删除导致调试断言的指针
- 断言一个与std::function兼容的函数指针
- 调试断言 使用指针时失败
- 访问指向像素openCV的指针时发生断言错误
- 断言错误,即使在使用 new 初始化字符指针后也是如此
- 调试断言失败:无效的空指针
- 断言(指针)引发分段冲突
- 循环迭代后共享指针断言失败
- 如何断言特定类的布局中没有任何vtbl指针
- 调试断言失败!无效空指针错误
- C++程序的断言失败,因为删除指针
- c++断言中的未定义行为:访问无效/空指针
- 自定义类指针的优先级队列断言错误