c++ - 删除指针的段错误

标签 c++ pointers segmentation-fault language-lawyer delete-operator

#include <iostream>
using namespace std;
class c1 {};
class c2 : public c1 {};
class c3 : public c1 {};
class c4 : public c2, public c3 {};

int main () {
  c4 *x1 = new c4;
  c3 *x2 = x1;
  delete x2; // segmentation fault
}

你好,我想了解类型转换和继承,我发现了这个问题。我有一个指向最派生类的指针,并且类型转换(隐式)到任何类的中间,在删除时,我认为它应该能够删除第一个新分配的空间。在某些编译器中,它看起来很好,但在 linux gcc 版本 4.7.2 (Debian 4.7.2-5) 中,它给出了段错误。想不通,为什么?任何帮助/指针/建议将不胜感激。

注意 - 类以菱形问题的形式导出。

最佳答案

这是未定义的行为。正如您所见,在某些情况下它可能看起来很有效,但在某些情况下却不会。

至少基类c3(或c1c2)应该有一个虚拟 析构函数。例如

class c3 : public c1 {
public:
    virtual ~c3() {}
};

根据标准,$5.3.5/3 Delete [expr.delete] :

(强调我的)

In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

关于c++ - 删除指针的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41800410/

相关文章:

c++ - 函数末尾的断点

c++ - 有没有办法在非模板类中定义模板成员?

c++ - *&aPtr 和 &*aPtr 有什么区别?

c - 如何检查指针是否已在 C 中释放?

c - 调试缓冲区溢出引起的段错误

debugging - 什么是段错误 rip/r​​sp 编号以及如何使用它们

c++ - 释放在 C++ 中的 std::string 中分配的内存

C++14 和 Visual Studio Code

C: 将 strtok token 分配给 char * 段错误

algorithm - 找到大于给定最小值的第一个斐波那契数