好的,所以我第一次嘗試C++,因爲它看起來像我將不得不使用它在即將到來的大學課程。我有幾年的編程經驗,但在非垃圾收集的世界中並沒有太多。關於手動內存管理和深度複製的新手問題
我有一個類,一個雙向鏈表中使用的節點。所以基本上它有一個值和兩個指向其他節點的指針。主構造器看起來像Node(const std::string & val, Node * prev, Node * next)
。練習包括一個複製構造函數,它執行另一個Node的淺表副本,並在其上面添加一條評論,表示要將其更改爲深度副本。
這是我認爲的意思:
Node(const Node & other)
: value(other.value)
{
prev = new Node(other.prev->value, other.prev->prev, other.prev->next);
next = new Node(other.next->value, other.next->prev, other.next->next);
}
這似乎實現使它以便更改複製的節點不會影響新節點的目標。但是,當我這樣做時,我正在堆上分配新東西。這讓我很擔心,因爲我認爲這意味着我也應該在Node的析構函數中刪除它。但是現在這與其他構造函數不一致,其中指向節點的指針剛剛被傳入,已經指向某個東西。我不能正確使用delete
ing next
和prev
與析構函數進行對吧?
我真的很困惑,指導表示讚賞!
編輯:這裏是代碼(我的上述變化前)的要求:
#include <string>
//! Node implements a doubly-linked list node
class Node {
friend class LinkedList; //!< LinkedList can access private members of Node
public:
//! Constructor
Node(const std::string & v, Node * p, Node * n) :
value(v), prev(p), next(n)
{
}
//! Change to deep copy
Node(const Node & other) :
value(other.value), prev(other.prev), next(other.next)
{
}
//! Read-only public methods for use by clients of the LinkedList class
const std::string & GetValue() const
{
return value;
}
Node * GetPrevious()const
{
return prev;
}
Node * GetNext()const
{
return next;
}
//! Change to deep copy
Node & operator=(const Node & other)
{
if(this!=&other)
{
value=other.value;
prev=other.prev;
next=other.next;
}
return *this;
}
private:
std::string value; //!< value stored in the node
Node * prev; //!< pointer to previous node in the list
Node * next; //!< pointer to next node in the list
};
您需要提供關於Node的更多信息:1)析構函數2)next/prev的類型3)是否嵌套在另一個類中4)如果整個類定義簡單。 – 2009-01-22 11:23:25
1)沒有析構函數。事實上,這是讓我困惑的事情之一。 2)節點* 3)它似乎被設計爲與LinkedList類一起使用,是 – 2009-01-22 18:17:05