【问题标题】:Cplex C++ interface. How to clean up memory?Cplex C++ 接口。如何清理内存?
【发布时间】:2013-06-12 15:50:37
【问题描述】:

背景:IBM ILOG Cplex 的 C++ 接口相当非常规地分配和取消分配内存:

声明 ILO 环境 IloEnv environment;,然后在此环境中构造模型和求解器,然后所有这些对象(包括环境)超出范围会导致内存泄漏。请注意,我没有使用 new 运算符。避免这种情况的一种方法是在对象超出范围之前调用environment.end();

设置: 现在,我有一个课程,其目的是解决特定的 ILP。这个类有一些成员变量:

IloEnv ilpEnvironment_;
IloObjective ilpObjective_;
IloExpr ilpExpression_;
IloModel ilpModel_;
IloCplex ilpSolver_;
IloNumArray ilpSolution_;
IloNumVarArray ilpVariables_;
IloNumArray ilpStartValues_;
IloRangeArray constraints_; 

这些成员变量在构造函数的初始化列表中被初始化:

inline MyClass::MyClass() 
:   ilpEnvironment_(),
    ilpObjective_(ilpEnvironment_),
    ilpExpression_(ilpEnvironment_),
    ilpModel_(ilpEnvironment_),
    ilpSolver_(ilpModel_),
    ilpSolution_(ilpEnvironment_),
    ilpVariables_(ilpEnvironment_),
    ilpStartValues_(ilpEnvironment_),
    constraints_(ilpEnvironment_)
{ /* ... */ }

析构函数取消分配所有内存(已由对成员变量进行操作的类的成员函数分配):

inline MyClass::~MyClass() {
    ilpEnvironment_.end();
}

问题:我如何实现一个成员函数void clear() 来释放内存并将类恢复到初始状态?以下是我进行的两次相当天真的尝试,但没有奏效:

inline void MyClass::clear() {
    ilpEnvironment_.end();
    ilpEnvironment_ = IloEnv(); // does not work, whether or not I comment this line out
    ilpObjective_ = IloObjective(ilpEnvironment_);
    ilpExpression_ = IloExpr(ilpEnvironment_);
    ilpModel_ = IloModel(ilpEnvironment_);
    ilpSolver_ = IloCplex(ilpEnvironment_);
    ilpSolution_ = IloNumArray(ilpEnvironment_);
    ilpVariables_ = IloNumVarArray(ilpEnvironment_);
    ilpStartValues_ = IloNumArray(ilpEnvironment_);
    constraints_ = IloRangeArray(ilpEnvironment_);
}

【问题讨论】:

    标签: memory-management memory-leaks cplex


    【解决方案1】:

    如果该类的目的是求解特定的 ILP 模型,那么我将使用模型大小/参数初始化该类,并在 solve() 成员函数中创建和销毁 CPLEX 对象,同时仅将结果保存为班级成员。类成员将是模型参数,而对象将隐藏所有 CPLEX 交易。

    你甚至可以有一个类成员来跟踪在特定的solve()调用中激活哪些约束。

    如果您绝对必须将 CPLEX 对象用作可更改的类成员,那么您可能想要尝试使用对象指针而不是对象本身作为类成员。调用 IloEnv::end() 会破坏与其关联的对象,因此您可以调用 IloEnd::end() 然后将指针重新分配给新对象。

    【讨论】:

      猜你喜欢
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      相关资源
      最近更新 更多