gpt4 book ai didi

c++ - 我需要一个用于 boost::ublas 矩阵的虚拟析构函数吗?

转载 作者:行者123 更新时间:2023-11-28 08:27:22 26 4
gpt4 key购买 nike

我在使用 boost::ublas 矩阵时需要虚拟析构函数吗?

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

最佳答案

你是说你有这个吗?

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

boost::ublas::matrix m;
};

这里没有任何内容要求你有一个虚拟析构函数。


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

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

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所以你知道它是做什么的,因为这听起来像是你只是把东西扔来扔去并希望它能起作用,这不是一个很好的方法。

关于c++ - 我需要一个用于 boost::ublas 矩阵的虚拟析构函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3488915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com