0
在C++中創建節點時,我何時需要使用new
運算符來確保內存可用於分配。在C++中聲明節點時,何時需要使用new運算符?
例如,此函數在聲明節點指針NewNode時不使用new
來查找現有鏈表的結尾,以便將節點添加到列表末尾,但在實際添加時使用new
該節點到列表的末尾。這是因爲節點指針被用作非動態內存分配,指向其他已經動態分配或由於其他原因分配的內存?在NewNode聲明前面使用new(nothrow)是不正確的語法還是邏輯判斷?
typedef Node* NodePtr; /*a type definition for NodePtr for ease of use in `the larger program this function is a part of*/`
void AddNode(char NewChar, NodePtr List)
{
NodePtr NewNode = List; //make NewNode point to List
while (NewNode->Link != NULL) //find end of linked list
NewNode = NewNode->Link;
NewNode->Link = new (nothrow) Node; //create a new Node at the end of the list
if (NewNode->Link == NULL) //make sure Node was created
return;
NewNode = NewNode->Link; //make NewNode point to the Node just created
NewNode->Ch = NewChar; //fill Ch part of NewNode
NewNode->Link = NULL; //make sure the list ends with NULL
}
void TestAddNode(NodePtr List)
{
char NewChar;
cout << "\n\n---------------- Testing AddNode -------------------\n\n";
cout << "Character to be added? ";
NewChar = cin.get();
cin.ignore();
if (NewChar == '\n') // User pressed just enter key.
{
cout << "Aborting AddNode...";
return;
}
cout << NewChar;
cout << " -- Adding \'" << NewChar << "\'";
AddNode(NewChar, List);
cout << "\n\nThe new list: ";
ShowList(List); //show list is another function that outputs the list
}
這通常不是一個好主意類型'typedef'原始指針類型。它更簡潔明確地用'*'表示法或'Ptr_'模板表示。用'typedef'必須尋找名稱的定義。 –
'NewNode'被誤導地命名。它既不是新節點也不是指向新節點的指針。一個更好的名字可能只是'p',這並不意味着這是一個指針。 –
更好的名字是ListIter – Pemdas