使用 boost::ublas 矩阵时是否需要虚拟析构函数?
顺便说一句,我的类是一个模板类。
你的意思是你有这个?
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;
请注意,它与基类中的成员无关。如果用户将通过指向基类的指针删除派生类,则始终需要虚拟析构函数。
我建议你买一本书,这样你就知道它做了什么,因为这听起来就像你只是扔东西并希望它有效,这不是一个很好的方法。