虚拟析构函数?

发布于 2024-12-29 02:08:16 字数 608 浏览 1 评论 0原文

出现一些错误,它是带有非虚拟析构函数的虚拟函数。我该如何修复这个错误?它在 g++ 4.6.x 中工作,但我需要它在旧版本的 g++ 上工作。 :(

#include <list>

template <typename T>
class container{
public:
    ~queue(){
        queuel.clear();
        queuel.~list();
    }
    virtual T func_x(){
        T temp;
        //do stuff with list<t> test
        return temp;
    }
private:
    std::list<T> test;
};

template <typename T>
class container2 : public container<T>{
public:
    virtual T func_x(){
        T temp;
        //do different stuff with list<T> test
        return temp;
    }
};

getting a couple errors that it's a virtual function with non-virtual destructor. how can i fix this error? it was working in g++ 4.6.x but i need it to work on an older version of g++. :(

#include <list>

template <typename T>
class container{
public:
    ~queue(){
        queuel.clear();
        queuel.~list();
    }
    virtual T func_x(){
        T temp;
        //do stuff with list<t> test
        return temp;
    }
private:
    std::list<T> test;
};

template <typename T>
class container2 : public container<T>{
public:
    virtual T func_x(){
        T temp;
        //do different stuff with list<T> test
        return temp;
    }
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪冰清 2025-01-05 02:08:16

编辑:@Als 有一点,析构函数也为您的类错误命名。更新了答案。

问题在于 g++ 认为既然类中有虚方法,就应该有虚析构函数。这与如果您继承一个类并扩展它有关,您可能会分配基类析构函数不知道清理的内存或其他资源,并且如果您的析构函数不是虚拟的,则可能会调用基类的析构函数在某些情况下,而不是真正的析构函数。

经验法则是,如果类中有虚拟方法,请使用虚拟析构函数。删除错误命名的析构函数 ~queue 并放入

virtual ~container();

类声明并在 .cpp 文件中实现析构函数应该可以解决您的问题。

Edit: @Als has a point, the destructor is also incorrectly named for your class. Updated answer.

The problem is just that g++ thinks that since you have virtual methods in the class, you should have a virtual destructor. This has to do with that if you inherit a class and extend it, you may allocate memory or other resources that the base class destructor has no idea about cleaning up, and if your destructor is not virtual, the base class' destructor may be called in some cases instead of your real destructor.

The rule of thumb is, if you have virtual methods in your class, use a virtual destructor. Removing the incorrectly named destructor ~queue and putting

virtual ~container();

in your class declaration and impementing the destructor in the .cpp file should fix your problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文