我最近阅读了有关RAII并已开始使用它。我试图将图定义为邻接列表,并使用unique_ptr
分配堆上的整个DS。我知道我可以将它们定义为堆栈对象,但我正在尝试使用unique_ptr
来适应它们。嵌套unique_ptr和stl容器
我做了以下
unique_ptr to vector --
|-->(unique_ptr)list<edge>
|-->(unique_ptr)list<edge>
|-->(unique_ptr)list<edge>
|-->(unique_ptr)list<edge>
代码:
#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
谁能帮助我纠正呢?
编辑:
我也不清楚哪些是向量是RAII类。 如果我做了以下
vector<int> *v;
v = new vector<int> (10);
我一定要删除该变量v
。或者当它超出范围时,它会自动释放堆上的内存吗?
编辑: 使用指针向量使用户负责内存管理。
你有什么错误? – OMGtechy
RAII并不一定是指智能指针。 'vector'和'list'是RAII自己完美的类;用'unique_ptr'管理它们不会添加任何东西。 –