2013-02-20 110 views
0

我有一个定义的结构包含一个std :: list。在我的代码中,我尝试遍历这个列表,但是我得到了一些奇怪的结果。std :: list.begin()给出空指针

struct my_struct_t { 
    std::list<int> my_list; 
    //More fields 
}; 

这是我在我的头文件中定义的结构。

而且在一个文件中的一些示例代码,其中包括这头将是:

std::list<int>::iterator my_iterator; 

    struct my_struct_t* test_struct = (struct my_struct_t*) malloc(sizeof(struct my_struct_t)); 
    my_iterator = test_struct->my_list.begin(); 
    printf("Beginning of list address: %p\n", my_iterator); 

    my_iterator = test_struct->my_list.end(); 
    printf("End of the list address: %p\n", my_iterator); 
    printf("Address of the list: %p\n", &(test_struct->my_list)); 

此代码编译并运行正常,但输出会是这样的:

Beginning of list address: (nil) 
End of the list address: 0x86f010 
Address of the list: 0x86f010 

最后两行对我来说非常有意义,因为列表应该是空的。但是如何/为什么我会在开始时得到一个空指针?我怎样才能解决这个问题?

+1

第1步:阅读一个很好的C++入门,从[那些]中选择一个(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。第2步:意识到尽管有许多相似之处,但C++和C语言却是截然不同的,只是其缺陷非常相似。 – 2013-02-20 07:23:31

回答

8

您不能malloc列表,然后使用它,而无需初始化。这是一个无效的操作。

尚未使用适当的new调用进行初始化。这完全可以工作,而不会造成段错误,这是惊人的。

您将需要使用C++样式初始化创建您的my_struct_t对象,否则它将不起作用。

你有没有尝试过的东西更类似于C++:

struct my_struct_t* test_struct = new my_struct_t; 

后来代替free叫你当然会delete

+1

你不需要一个新的调用..但至少需要调用构造函数 – Kek 2013-02-20 07:20:44

+1

调用一个'malloc''对象的构造函数似乎是一条危险的道路。如果'list'有一个析构函数,你必须在发布'free'之前手动调用它。 – tadman 2013-02-20 07:22:06

+0

是的。我的意思是:你可以在栈上创建你的sctruct ...或者为结构调用一个新的,而不是列表 – Kek 2013-02-20 07:25:29

1

malloc只会为对象分配必要的内存,但不会初始化该对象。 C++中的对象的初始化由其构造函数执行。 C++提供运算符new来分配内存并同时初始化一个对象。所以,你应该做的是:

my_struct_t* x = new my_struct_t(); 

如果你真的打算在这里使用malloc,你仍然可以正常在正确对齐原始内存使用placement new初始化的对象。请记住,您将不得不显式地调用析构函数并显式释放内存。但我严重怀疑这是你的意图。