【问题标题】:Do I need a virtual destructor for boost::ublas matrix?我是否需要 boost::ublas 矩阵的虚拟析构函数?
【发布时间】:2011-03-30 04:04:34
【问题描述】:

使用 boost::ublas 矩阵时是否需要虚拟析构函数?

顺便说一句,我的类是模板类。

【问题讨论】:

    标签: c++ templates boost virtual-destructor


    【解决方案1】:

    你的意思是你有这个吗?

    template <typename Whatever>
    struct my_class
    {
        // ...
    
        boost::ublas::matrix m;
    };
    

    这里没有任何东西表明你有一个虚拟析构函数。


    当您打算让用户公开从您的类派生时,您需要一个虚拟析构函数。所以这个问题应该是“用户将公开从我的类派生,我需要一个虚拟析构函数吗?”。是的,你会的。

    原因是这样做会导致未定义的行为:

    struct base {}; // no virtual destructor
    struct derived : base {};
    
    base* b = new derived;
    
    // undefined behavior, dynamic type does not match static type,
    // and the base class does not have a virtual destructor
    delete b; 
    

    这不是:

    struct base { virtual ~base(){} }; // virtual destructor
    struct derived : base {};
    
    base* b = new derived;
    
    // well-defined behavior, dynamic type does not match static type,
    // but the base class has a virtual destructor
    delete b; 
    

    请注意,它与基类中的成员无关。如果用户将通过指向基类的指针删除派生类,您总是需要一个虚拟析构函数。


    我会推荐你​​get a book,这样你就知道它做了什么,因为听起来你只是扔东西并希望它有效,这不是一个很好的方法。

    【讨论】:

    • 是的@第一个问题是我的班级是什么样的,是的,我打算让用户从我的班级派生。真的非常感谢:)
    • @ismail:哦,那么澄清一下:你确实需要virtual
    猜你喜欢
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 2014-03-23
    • 2023-02-01
    相关资源
    最近更新 更多