与 boost odeint 集成期间的析构函数调用
Destructor calls during integration with boost odeint
如果我将一个系统与 boostsodeint
模块集成,使用类来定义导数,则经常调用此类的析构函数。
- 这种行为是有意的吗?
- 为什么会这样呢?
- 如果我想在此类中动态分配数组,该怎么办?
例如,此代码:
#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++ 的初学者)
析构函数仅在程序结束时调用一次,如果
- 在 main 和
foo
- 如果在调用
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 样式数组解决这个问题需要花费大量时间来调试。
- 析构函数调用
- 在具有向量的类构造函数中进行析构函数调用
- 从 c++ 中派生类的析构函数调用虚函数
- C++析构函数调用两次,堆栈分配的复合对象
- C++ 在析构函数调用之前删除的动态成员数组
- 析构函数调用c++中的一个向量
- Singleton模式中的手动析构函数调用:调用多次
- 从内部类的析构函数调用虚拟函数
- 与 boost odeint 集成期间的析构函数调用
- 堆栈展开如何与析构函数调用有关?
- C++:优化析构函数调用
- 以逗号分隔的表达式中的析构函数调用
- GCC 9.1 返回 void& 作为显式析构函数调用的结果类型。这是一个错误吗?
- 从C++中的虚拟析构函数调用虚拟方法
- 从指针返回对象时出现意外的析构函数调用
- 使用 decltype 显式析构函数调用
- C++析构函数调用了错误的对象
- 了解虚拟函数和析构函数调用
- 多重继承析构函数调用他自己和父析构函数?c++
- 析构函数调用表单不适当的库