添加
演练时间:
void collection::add(card a) // pass by value. a is a copy
{
card *temp = new card(a); // makes a dynamically allocated copy of the copy.
temp->next = start; // looks right
start = temp; // looks right
}
这个函数没有明显的错误,但是如果你愿意的话
myCollection.add(mycard);
然后期望使用mycard 就好像它在myCollection 中一样,那么你就不走运了。 mycard 的副本位于 mycollection。我们可以做些小改进来减少复制量,
void collection::add(const card & a) // pass by reference. a is the source. One less copy
// Look up const correctness for more information
// on the use of const here
{
card *temp = new card(a); // makes a dynamically allocated copy of the copy.
temp->next = start;
start = temp;
}
但如果您希望 mycard 出现在列表中而不是其中的一部分,您需要以非常不同的方式做事
void collection::add(card * a) // pass by reference via a pointer
{
a->next = start;
start = a;
}
并像这样使用它:
card * mycard = new card()
// set members of *mycard. Or better, make a smarter constructor to set them for you
myCollection.add(mycard);
删除
card collection::deal(){
card *temp = start->next; //temp points to the second item on the list
start->next = nullptr; // cur off start from the rest of the list
start = temp; // whups! Just lost the first item in the list
return start; // start is a pointer. The return type is not. Need to dereference
}
修复一个:尊重指针以返回它。
card collection::deal(){
card *temp = start->next;
start->next = nullptr;
start = temp;
return *start; // returns a copy of the second card in the list
}
下一个修复:返回正确的卡
card collection::deal(){
card *temp = start; //temp points to the first item on the list
start = start->next; // advance start to second item on the list
temp->next = nullptr; // cut former first item off from from the list
return *temp; // returns a copy of the former first item. But what of temp?
}
下一个修复:temp 被泄露。没有人指向它,内存从未被释放。
card collection::deal(){
card *temp = start;
start = start->next;
temp->next = nullptr;
card rval(*temp); // copy former first node
delete temp; // free former first node
return rval; // return copy.
}
您还可以返回指向已删除项目的指针并将其释放给调用者。这有点狡猾。
card * collection::deal(){
card *temp = start; //temp points to the first item on the list
start = start->next; // advance start to second item on the list
temp->next = nullptr; // cut former first item off from from the list
return temp; // returns former first item
}
Look into std::unique_ptr 作为一个工具来确保返回的card 指针被调用者释放。
另一种可能是将链表与card 分开,这样collection 的用户只能看到cards,不知道cards 是如何存储在collection 中的。