我有一个头文件,我在其中定义方法。我最终试图实现一个双向链表来存储对的数据。 这是cont.h
template <class Key, class T> class storage;
template < class Key, class T, class Compare = std::less<Key> >
class cont{
private:
storage <Key, T> data;
public:
typedef size_t size_type;
typedef Key key_type;
typedef T mapped_type;
//default constructor
cont(){}
cont(key_type k, mapped_type m)
{
std::pair<Key, T> x = std::make_pair(k,m);
data.begin_list(x);
//std::pair<Key, T> a = std::make_pair(k,m);
//data.push(a);
}
};
template <class Key, class T>
struct node
{
node *prev, *next;
std::pair<Key, T> node_data;
};
template <class Key, class T>
class storage{
private:
node <Key, T> *head;
node <Key, T> *tail;
node <Key, T> *curr;
int size;
public:
//default ctor
storage(){}
void begin_list(std::pair <Key, T> h)
{
size=1;
//bottom two lines induce segmentation fault
//head->node_data=h;
//head->prev=NULL;
}
};
main.cc将如下所示:
#include "cont.h"
int main() {
cont<double, int> s(6.6, 3);
}
我不明白为什么会遇到段错误。我应该为每个节点动态分配内存吗?
答案 0 :(得分:1)
好吧,head
尚未在执行begin_list
时初始化,因此取消引用它会为您提供未定义的行为:
void begin_list(std::pair <Key, T> h)
{
size=1;
head->node_data=h; // <= DEREFERENCING head WITHOUT HAVING INITIALIZED IT
head->prev=NULL; // <== SAME HERE
}
这里你可能想在node
的构造函数中动态分配storage
类型的对象,将相应的new
表达式的结果赋给head
(然后使tail
和curr
指向同一个对象。
但是,请考虑 not 使用new
,delete
和原始指针进行内存管理。更喜欢使用智能指针来表达所有权。