2014-02-20 63 views
1

我正在C++中重新創建一個鏈表,並且在重載+ =操作符時出現壞指針。我想我只是以錯誤的方式使用分配器,但我可能是錯的。C++ std :: allocator :: allocate()給我一個不好的指針

這裏是上下文:

void MyLinkedList::operator+=(const std::string& s) 
{ 
    allocator<Node> a; 
    Node* n = a.allocate(1); 

    Node node(s); 
    (*n) = node; 
    if (first == NULL) 
     first = n; 
    else 
    { 
     (*current).SetNext(n); 
     current = n; 
    } 
} 

其中firstcurrentNode*類型。 在此先感謝!

+0

你得到了什麼錯誤? – Brian

回答

3

std::allocator分配原始非構造存儲。要使用存儲,您必須使用.construct()

a.construct(n, /* initializer */); 
+0

謝謝!現在,當將舊指針設置爲'current'指向的'Node'中的'Node * next'時,我遇到了麻煩。它告訴我在該書寫位置存在訪問違規。我已經Google了一下,看起來好像我可能已經在只讀內存中創建了我的Node。我有,如果是的話,我該如何把它放在可寫入的內存中? – user3280133

相關問題