c++ - 当我尝试删除 char* 时调试断言失败

标签 c++ char virtual-destructor

我是 C++ 的新手,正在学习虚函数,并且知道如果类具有虚函数并且类具有指针成员,则必须编写虚析构函数。下面是我的代码,我使用的是 Virtual Studio 2013RC

#include<iostream>

using namespace std;
//base and derived class with virtual function
class Parent{
protected:
    const char *name;
public:
    virtual void say(){ cout << "1" << endl; }
    virtual void showName(){ cout << name << endl; }
    Parent(){};
    Parent(const char *myName) :name(myName){};
    virtual ~Parent(){ delete name; cout << "Parent name deleted" << endl; }
};

class Child :public Parent{
protected:
    const char *name;
public:
    virtual void say(){ cout << "2" << endl; }
    virtual void showName(){ cout << name << endl; }
    Child(){};
    Child(const char *myName) :name(myName){};
    virtual ~Child(){ delete name; cout << "Child name deleted" << endl;}
}; 

int main(){
    Child a("Tom");
    return 0;
}

或者

int main(){
    Parent *a = new Child("Tom");
    delete a;        
    return 0;
}

两者都会给出调试断言失败的错误窗口。 enter image description here

对于这种情况,应该如何正确编写虚拟析构函数?

非常感谢

最佳答案

因为你试图删除一个文字字符串指针。您将 Child::name 成员设置为指向文字字符串 "Tom",这是一个指向编译器创建的内存的指针。您应该只删除您明确新建的内容。

另请注意,ParentChild 类各有不同且截然不同的name 成员变量。当您初始化 Child::name 变量时,Parent 中的变量仍未初始化。

关于c++ - 当我尝试删除 char* 时调试断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20934079/

相关文章:

c++ - 继承层次结构中的析构函数顺序

C++ - 安全指针范围?

c++ - 寻找对我的读者/作家实现的批评

C++构造函数(速度)

C++ 2440 错误 - 编译器认为字符串是 const char?

c - 网络编程中char数组的问题

c++ - C++中虚类和extern的使用

c++ - 尝试计算二维数组中的特定字符,但计算整个数组

c++ - Keil:虚拟或 protected 析构函数和堆

c++ - 不用于删除对象的基类的析构函数应该是虚拟的吗?