我使用unique_ptr
与正常指针混合实现了一个单链表。是否正在给一个unique_ptr指定一个正常指针?
我有这样的代码:
template<typename B>
void linkedlist<B>::addNode(B x){
node * n = new node; //initialize new node
n->x = x;
n->next = nullptr; //smart pointer
if(head == nullptr){ //if the list is empty
head = (unique_ptr<node>)n; //cast the normal pointer to a unique pointer
}else{ //if there is an existing link
current = head.get(); //get the address that is being
//pointed by the unique_ptr head
while(current->next != nullptr) //loop until the end then stop
current = (current->next).get();
current->next = (unique_ptr<node>) n; //connect the new node to the last node
}
}
我听说,这是一个不好的做法,如果是的话那么谁能告诉我,为什么?建议和正确的做法提示也将不胜感激。
直接使用'auto n = std :: make_unique();'和'head = std :: move(n);'以避免所有的投射。 –
Jarod42
我明白了,让我试试看。 –
为什么你的缩进如此混乱?什么阻止你纠正这一点? –