与 boost odeint 集成期间的析构函数调用

Destructor calls during integration with boost odeint

本文关键字:析构 函数调用 boost odeint 集成      更新时间:2023-10-16

如果我将一个系统与 boostsodeint模块集成,使用类来定义导数,则经常调用此类的析构函数。

  1. 这种行为是有意的吗?
  2. 为什么会这样呢?
  3. 如果我想在此类中动态分配数组,该怎么办?

例如,此代码:

#include <iostream>
#include <boost/numeric/odeint.hpp>
using namespace std;
using namespace boost::numeric::odeint;
class foo
{
public:
virtual ~foo() {
std::cout << "destructor called" << std::endl;
}
void operator()(const double &x, double &dxdt, double t) const    {
dxdt = 1;
}
};
int main( int argc , char **argv )
{
double x = 0;
const double dt = 0.1;
typedef runge_kutta4< double > stepper_type;
integrate_const( stepper_type() , foo(), x , 0.0 , 10.0 , dt);
return 0;
}

调用析构函数大约 400 次。(我是 c++ 的初学者)

析构函数仅在程序结束时调用一次,如果

  1. 在 main 和foo
  2. 如果在调用integrate_const()中使用了std::ref()

喜欢这个:

#include <iostream>
#include <boost/numeric/odeint.hpp>
#include <functional>
using namespace boost::numeric::odeint;
class foo
{
public:
virtual ~foo() {
std::cout << "destructor called" << std::endl;
}
void operator()(const double &x, double &dxdt, double t) const   {
dxdt = 1;
}
};
int main( int argc , char **argv )
{
double x = 0;
const double dt = 0.1;
typedef runge_kutta4< double > stepper_type;
foo myfoo;
integrate_const( stepper_type() , std::ref( myfoo ), x , 0.0 , 10.0 , dt);
return 0;
}

您可以在 foo 类中动态分配任何类型的数据,例如通过添加一个简单的 setter 函数.setData(),该函数可以从main

myfoo.setData(myArray);

在呼叫integrate_const()之前。

很简单:只需将调试器中的调用追溯到析构函数即可。

您将看到第一级是:

template<class Stepper, class System, class State, class Time> size_t integrate_const( Stepper stepper, System system, State &start_state, Time start_time, Time end_time, Time dt)

经过几个中间步骤后,其中有一个循环:

while( less_eq_with_sign( static_cast<Time>(time+dt) , end_time , dt ) ) { obs( start_state , time ); st.do_step( system , start_state , time , dt ); ...

usr/include/boost/numeric/odeint/integrate/detail/integrate_const.hpp:59发现

不幸的是,所有参数都是通过值向下发送的,而不是在提升代码中的引用。因此,它将根据您创建的对象创建和销毁许多临时对象。

如果你想动态分配数组,我建议使用std::vector因为通过 C 样式数组解决这个问题需要花费大量时间来调试。