【问题标题】:unique_ptr with polymorphic type not being deleted未删除多态类型的 unique_ptr
【发布时间】:2013-08-10 01:16:30
【问题描述】:

我有一个 unique_ptrs 向量到使用基类存储的派生类型

std::unique_ptr<std::vector<std::unique_ptr<Variable>>> decisionVariables;

Variable 是超类,派生类型是 Route 类。我的问题是,当包含决策变量的类被删除时,路由实例似乎没有被删除。

Route 派生自变量:

#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

有没有办法防止目前出现严重的内存泄漏?

【问题讨论】:

  • 保留带有双下划线的名称。不要使用它们。
  • 你不是缺少虚拟析构函数吗?

标签: c++ unique-ptr


【解决方案1】:

您的抽象基类Variable 没有虚拟析构函数,因此您不能使用指向该类的指针删除派生类的对象。这正是unique_ptr&lt;Variable&gt; 在被销毁时会尝试做的事情。

这将导致未定义的行为 - 最可能的行为是派生类的析构函数没有被调用,因此它管理的任何资源都会泄漏。

最简单的解决方法是基类中的虚拟析构函数:

virtual ~Variable() {}

【讨论】:

  • 我在其他帖子上看到了这个解决方案,但也在派生类(Route)中实现了一个析构函数。非常感谢您的快速回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-19
  • 2014-05-20
  • 2019-08-26
  • 2015-02-04
  • 1970-01-01
  • 2017-05-15
相关资源
最近更新 更多