2014-02-17 104 views
0

我最近阅读了有关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。或者当它超出范围时,它会自动释放堆上的内存吗?

编辑: 使用指针向量使用户负责内存管理。

+0

你有什么错误? – OMGtechy

+1

RAII并不一定是指智能指针。 'vector'和'list'是RAII自己完美的类;用'unique_ptr'管理它们不会添加任何东西。 –

回答

4

unique_ptr s为不必要的。只需使用这些对象本身:

vector<list<edge>> adj_list; 

RAII并不意味着智能指针,它是相反的方式。 C++在智能指针之前就已经适应了RAII。

2

看看vector的施工专家here。它们都不接受指向元素的指针。因此,无论使用vector<list<struct edge>*>或改变调用此:

list<struct edge> emptyList; 
... (new vector<list<struct edge> >(10, emptyList));