Unique_ptr with a polymorphic type that cannot be deleted

I have a unique_ptrs vector in a derived type store using the base class

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

Where the Variable is the superclass, and the derived type is the Route class. My problem is that route instances do not seem to be deleted when the class containing the deciding variables is deleted.

The route is obtained from the variable:

 #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 

Header file for the route:

 #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 

Is there a way to prevent a serious memory leak at the moment?

+4
source share
1 answer

Your abstract base class Variable does not have a virtual destructor, so you cannot delete an object of a derived class with a pointer to this class. This is exactly what unique_ptr<Variable> will try to do when it is destroyed.

This will lead to undefined behavior - the most likely behavior is that the destructor of the derived class is not called, so any resources it manages will flow.

The simplest solution is a virtual destructor in the base class:

 virtual ~Variable() {} 
+7
source

Source: https://habr.com/ru/post/1496199/


All Articles