[英]Do I need a virtual destructor for boost::ublas matrix?
使用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;
請注意,它與基類中的成員無關 。 如果用戶將通過指向基類的指針刪除派生類,則始終需要虛擬析構函數。
我建議您拿一本書,以便您知道它的作用,因為這聽起來像是您隨便扔東西並希望它能起作用,但這不是一個很好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.