2013-02-20 97 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初始化的對象。請記住,您將不得不顯式地調用析構函數並顯式釋放內存。但我嚴重懷疑這是你的意圖。