【问题标题】:Virtual Destructor Not called in Base as well as Derived Class虚拟析构函数未在基类和派生类中调用
【发布时间】:2015-02-24 10:25:28
【问题描述】:

以下代码涉及 4 个类。

  1. 基类是 Person 类,有两个派生类 Student 和 Lecturer。每个人都支持两个函数:toString() 和 type()。 Type() 返回该类的名称,而 toString() 打印实例的信息(学生或讲师)。

  2. Person 是抽象类,但 Student 和 Lecturer 都是具体类。

以上两个功能我已经实现了。

  1. 许多讲师将共享指向同一个 SalaryTable 的指针,可能还有其他 SalaryTable(支持相同的功能)并且讲师不拥有 SalaryTable。此外,它们每个都有一些额外的功能。

谁能单独解释第三点?据我所知,我使用了 Lecturer 构造函数中给出的 SalaryTable 指针,并将其分配给了我在 Lecturer.h 中添加的 SalaryTable 指针 (salaryTable_)。然后我使用salaryTable_->annualSalary(grade_) 返回薪水。在 ~Lectuere() 的析构函数中,我做了一个 deletesalaryTable_。

这样做是否正确?当我这样做时,只会调用 ~Salary() 析构函数,并且不会调用基类析构函数 (~Person()) 和派生类析构函数 (~Student() & ~Lecturer())。谁能解释一下我哪里错了?

main.cpp

int main(int argc, char* argv[]) {

    if (argc == 1) {
        SalaryTable st;
        Person* arr[2];
        arr[0] = new Student("Apolo",5);
        arr[1] = new Lecturer("Zeus","CO7100",33,&st);

        for (unsigned int i=0 ; i<2 ; ++i) {
            if (arr[i]->type() == "Student") {
                Student* s=dynamic_cast<Student*>(arr[i]);
                s->addMCF("blah blah");
                s->addMCF("");
                s->addMCF("Something else");
            }
        }
        for (unsigned int i=0 ; i<2 ; ++i) {
            cout << *arr[i] << endl;
        }
    }
}

SalaryTable.h

#ifndef SALARYTABLE_H_
#define SALARYTABLE_H_

class SalaryTable {
public:
    SalaryTable();
    ~SalaryTable();

    unsigned int annualSalary(unsigned int grade) const;
};

#endif /* SALARYTABLE_H_ */

人.h

#ifndef PERSON_H_
#define PERSON_H_

#include <string>
#include <iosfwd>
#include <vector>

#include "SalaryTable.h"

using std::vector;
using std::string;

class Person {
public:
    Person() = delete;
    Person(const Person&) = delete;
    Person(Person&&) = delete;

    Person(const char* name);
    Person(const std::string& name);
    virtual ~Person();

    // Return the name of the Person
    // Should be supported by all Persons.
    std::string name() const;

    virtual std::string toString() const=0;

    virtual std::string type() const=0;

    friend std::ostream& operator<<(std::ostream&, const Person&);
private:
    std::string name_;
};

学生.h

class Student: public Person {
public:
    Student() = delete;
    Student(const Student&) = delete;
    Student(Student&&) = delete;

    Student(const char* name, unsigned int studentId);
    Student(const std::string& name, unsigned int studentId);
    virtual ~Student();

    void addMCF(const std::string&);
    std::string MCF(unsigned int);

    unsigned int id() const;

    std::string toString() const;
    std::string type() const;

private:
    unsigned int studentId_;
    vector<string> vec_;
};

讲师.h

class Lecturer: public Person {
public:
    Lecturer() = delete;
    Lecturer(const Lecturer&) = delete;
    Lecturer(Lecturer&&) = delete;

    Lecturer(const char* name, const char* teaches, unsigned int grade,
            SalaryTable*);
    Lecturer(const std::string& name, const std::string& teaches,
            unsigned int grade, SalaryTable*);
    virtual ~Lecturer();

    void increaseGrade();
    unsigned int salary() const;

    void changeModule(const std::string& newModule);
    std::string teaches() const;

    std::string toString() const;
    std::string type() const;

private:
    string teaches_;
    string module_;
    unsigned int grade_;
    SalaryTable& salaryTable_;

};

#endif /* PERSON_H_ */

注意:请注意,我无法更改 .h 文件。

我收到了很多关于销毁指针的意见。但我的终极问题是:为什么除了 SalaryTable 类之外的所有其他类都没有被破坏。我通过在所有类的析构函数中打印一个 stmt 来验证它。任何人都可以对此有所了解。

“还添加了 main.cpp 文件,我也无法修改它。”

【问题讨论】:

  • 有问题的代码在哪里?为什么你认为我们有心灵感应?
  • 问题的标题可能有点误导。我想真正的问题涉及在每个Lecturer 中处理SalaryTable 的所有权。
  • 由于Lecturer 类不拥有指向SalaryTable 的指针,它应该删除它。
  • @Cheers 和 hth。 -Alf,我也添加了实现代码
  • @DhiwaTdG:这很好,但出现问题的代码是使用这些类的代码。猜测代码具有Person 的向量或数组。但在你展示它之前,它需要心灵感应的力量才能确定。发布代码示例的简单规则是(在可能的情况下)读者应该能够编译并运行它并查看问题。我可以编译并运行您发布的代码吗?

标签: c++ inheritance c++11 destructor virtual-functions


【解决方案1】:

您必须决定谁拥有SalaryTable,每个Lecturer 在构造时都会收到一个指向的指针。 有两个类似的选项。

(1) 该表由另一个类/代码明确拥有(未在您的问题中显示),那么 Lecturer 应该保留一个 观察指针 (或引用)到该表(a const SalaryTable*constSalaryTable&amp; 或类似的)从未用于 delete 代码布局必须保证 SalaryTable 在任何 Lecturer 观察它之前不会被破坏。

(2) 您可以使用std::shared_ptr 确保后者,但这需要付出一定的代价,也意味着SalaryTable 没有所有者,但所有保留shared_ptr 的代码部分它共同拥有所有权。

对我来说 (1) 看起来更合乎逻辑:SalaryTable 是一个独立于任何Lecturer 存在的基本对象,应该在任何Lecturer 之前创建并在任何Lecturer 之后销毁。如果您没有相关经验,我也建议避免使用shared_ptr

【讨论】:

  • 回复const SalaryTabl*const,最后的const 没有任何用处。值得注意的是,观察指针和所指对象的常量是不相关的正交问题。 IE。那第一个const与观察指针的概念无关。否则很好地争论答案和建议。 ;-)
  • 我在 Lecturer 类中引入了对 SalaryTable 的 const 引用。是这样的吗?
  • @Cheersandhth.-Alf 我重新措辞了我的回答以反映您的批评。不过,我不太同意你的说法,即班级成员 const T*const 中的最后一个 const 没有任何用处。它将该类成员表示为const 成员,它必须由构造函数初始化并且此后永远不会更改(即使const_cast 也不更改)。在某些情况下,这使编译器能够优化代码。
【解决方案2】:

这不是正确的方法:薪水表是在讲师的构造函数中给你的。如果你在讲师的析构函数中删除它,共享同一张表的所有其他讲师都会受到影响。

正确的方法是让创建表的调用者在不需要 longuet 时将其销毁。

最好的方法是将指向共享薪水表的原始指针替换为共享指针,然后共享指针可以自动跟踪其使用情况并在不再需要时销毁对象

【讨论】:

  • 我很清楚你的意思。但恐怕我无法修改我的 .h 文件。
  • 我在 Lecturer 类中引入了对 SalaryTable 的 const 引用。是这样的吗?
  • 在您编辑的代码中,薪水表是 if 块中的本地对象。一旦你离开 if 块,它就会被销毁,而用 new 动态创建的对象会活得更久。
【解决方案3】:

SalaryTable 实例被销毁,因为它是一个本地自动变量。

其他对象不会被销毁,因为它们是使用 new 动态分配的,没有相应的 delete 调用(也没有智能指针来执行此操作)。

就这么简单。


顺便说一句,正如其他答案中提到的,您不应该让对象delete 拥有它不拥有的东西。

每个讲师都只有一个指向薪水表的非所有者指针。

这意味着只要引用的讲师对象存在,代码就必须确保引用的薪水表存在。通常这是通过智能指针完成的。由于您无法更改标题,因此您必须更手动地确保它。

【讨论】:

    【解决方案4】:

    谁能单独解释第三点?据我所知,我使用了 Lecturer 构造函数中给出的 SalaryTable 指针,并将其分配给我在 Lecturer.h 中添加的 SalaryTable 指针 (salaryTable_)。然后我使用salaryTable_->annualSalary(grade_) 返回薪水。在 ~Lectuere() 的析构函数中,我做了一个 deletesalaryTable_。

    您的方法存在问题:第三个主题指出讲师不拥有薪水表,并且可以在多个讲师之间共享。像这样在构造函数中删除意味着表的唯一所有权,事实并非如此。

    这可能取决于程序的其余逻辑,但这里最好的方法之一是创建指向表的共享智能指针,而不是原始指针。你的声明会变成这样:

        // ...
        Lecturer(const char* name, const char* teaches, unsigned int grade,
            std::shared_ptr<SalaryTable>);
        Lecturer(const std::string& name, const std::string& teaches,
            unsigned int grade, std::shared_ptr<SalaryTable>);        
        // ...
        std::shared_ptr<SalaryTable> salaryTable_;
    

    而且没有必要明确删除它们。


    考虑到您的最新编辑:如果无法更改类的接口,则必须采取其他措施来管理薪金表和人员实体。您必须确保在讲师创建之前创建薪水表(我想这已经发生了),并且在讲师创建之后将它们销毁。智能指针也可以在主程序中使用,但可能根本不需要。

    我收到了很多关于销毁指针的意见。但我最终的问题是:为什么除了 SalaryTable 类之外的所有其他类都没有被破坏。我通过在所有类的析构函数中打印一个 stmt 来验证它。任何人都可以对此有所了解。

    嗯,这仅意味着这些对象没有被正确处理,如上段所述。现在您提供了代码,我们可以确定给定的表是堆栈分配的,除了它的析构函数之外不需要额外的内存管理。请注意析构函数只会在 st 超出范围时被调用,因此它应该在 if 块的末尾被销毁。

    【讨论】:

    • 我很清楚你的意思。但恐怕我无法修改我的 .h 文件。
    • @DhiwaTdG 在这种情况下,您将不得不考虑其他形式的内存管理。如果你能保证在讲师结束后销毁工资表,那么我想你可以在这里保留原始指针。这不是最好的方法,但如果没有其他信息,我们无能为力。
    • 我在 Lecturer 类中引入了对 SalaryTable 的 const 引用。是这样的吗?
    • 还添加了 main.cpp 文件,我无法修改它。
    • 我已经更新了答案。似乎没有理由不破坏该表。应该在 if 块的末尾清理它就好了。
    猜你喜欢
    • 2018-07-06
    • 2011-03-16
    • 2013-11-01
    • 2015-04-16
    • 2021-08-22
    • 2011-09-27
    • 2021-01-31
    • 1970-01-01
    • 2014-10-02
    相关资源
    最近更新 更多