[英]unique_ptr with polymorphic type not being deleted
我有一個使用基類的unique_ptrs向量到派生類型存儲
std::unique_ptr<std::vector<std::unique_ptr<Variable>>> decisionVariables;
其中Variable是超類,派生類型是Route類。 我的問題是,當刪除包含decisionVariables的類時,似乎沒有刪除路由實例。
路由從變量派生:
#ifndef __VARIABLE__
#define __VARIABLE__
/**
* Interface for decision variables.
*/
#include <cstring>
#include <ostream>
#include <memory>
class Variable {
public:
/**
* Returns an independent copy of this decision variable.
*
* @ret a copy of this decision variable
*/
virtual std::unique_ptr<Variable> copy () = 0;
virtual std::string toString () = 0;
};
#endif
路線的頭文件:
#ifndef __ROUTE__
#define __ROUTE__
#include <vector>
#include <map>
#include <cstring>
#include <sstream>
#include <ostream>
#include <memory>
#include <set>
#include <algorithm>
#include "../../../Framework/h/core/Variable.h"
class Route : public Variable {
private:
std::unique_ptr<std::vector<int>> route;
double frequency;
double routeLength;
public:
Route ();
void add (int);
void addToFront (int);
void remove ();
void removeFromFront ();
std::vector<int>::iterator begin();
std::vector<int>::iterator end();
int size ();
std::vector<int> getViableNodes (std::shared_ptr<std::map<int, std::unique_ptr<std::vector<int>>>>, int);
int front ();
int back ();
std::string toString ();
int get (int);
bool containsLink (int, int);
bool contains (int);
void replace (int, int);
void setFrequency (double);
double getFrequency ();
void setRouteLength (double);
double getRouteLength ();
std::unique_ptr<Variable> copy ();
};
#endif
有沒有辦法防止此刻經歷的嚴重內存泄漏?
您的抽象基類Variable
沒有虛擬析構函數,因此您無法使用指向該類的指針刪除派生類的對象。 這正是unique_ptr<Variable>
在銷毀時會嘗試做的事情。
這將導致未定義的行為 - 最可能的行為是派生類的析構函數未被調用,因此它管理的任何資源都將泄漏。
最簡單的修復是基類中的虛擬析構函數:
virtual ~Variable() {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.