Your unique_ptr
s are unnecessary. Just use the objects themselves:
vector<list<edge>> adj_list;
RAII does not imply smart pointers, it's the other way around. C++ accomodated RAII long before smart pointers.
문제
I have recently read about RAII and have begun using it. I am trying to define graph as adjacency list and allocate the entire DS on heap using unique_ptr
. I know that I can define them as stack objects, but I am trying to use unique_ptr
's to get used to them.
I am doing the following
unique_ptr to vector --
|-->(unique_ptr)list<edge>
|-->(unique_ptr)list<edge>
|-->(unique_ptr)list<edge>
|-->(unique_ptr)list<edge>
Code:
#include<memory>
#include<vector>
#include<list>
using namespace std;
struct edge {
int vertex;
int weight;
};
int vertices = 10;
unique_ptr<vector<unique_ptr<list<struct edge > > > >
adj_list(new vector<list<struct edge> >(10)); // THIS COMPILES
unique_ptr<vector<unique_ptr<list<struct edge > > > >
adj_list(new vector<list<struct edge> >(10, new list<edge>())); //THIS GIVES COMPILATION ERROR
Can anyone help me correct this?
EDIT:
I have doubt regarding vector being RAII classes. if I do the following
vector<int> *v;
v = new vector<int> (10);
Do I have to delete the variable v
. Or will it automatically free the memory on heap, when it goes out of scope ?
EDIT: using pointer to vector makes the user responsible for memory management.
해결책
Your unique_ptr
s are unnecessary. Just use the objects themselves:
vector<list<edge>> adj_list;
RAII does not imply smart pointers, it's the other way around. C++ accomodated RAII long before smart pointers.
다른 팁
Look at vector
's constructors here. None of them accepts a pointer to the element. So either use vector<list<struct edge>*>
or change the call to this:
list<struct edge> emptyList;
... (new vector<list<struct edge> >(10, emptyList));