开发者

Do I need a virtual destructor for boost::ublas matrix?

开发者 https://www.devze.com 2023-01-11 21:16 出处:网络
Do I need virtual destructor when I am using boost::ublas matrix ? By the way开发者_JS百科, my class is a template class.Do you mean you have this?

Do I need virtual destructor when I am using boost::ublas matrix ?

By the way开发者_JS百科, my class is a template class.


Do you mean you have this?

template <typename Whatever>
struct my_class
{
    // ...

    boost::ublas::matrix m;
};

There's nothing here that dictates you have a virtual destructor.


You want a virtual destructor when you intend on having users publically derive from your class. So that question should be "Users will publically derive from my class, do I need a virtual destructor?". Yes, you do.

The reason is that doing this leads to undefined behavior:

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; 

This does not:

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; 

Note that it has nothing to do with what members there are in the base class. You always need a virtual destructor if users will be deleting derived classes through a pointer to a base class.


I would recommend you get a book so you know what it does, because it sounds like you just throw things around and hope it works, which isn't a very good approach.

0

精彩评论

暂无评论...
验证码 换一张
取 消