我使用 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
}
}
我听说这是一种不好的做法,如果是的话,有人能告诉我为什么吗?对于正确做法的建议和技巧也将不胜感激。
最佳答案
虽然强制转换语法有点奇怪,但它完全等同于更常规的语法
unique_ptr<node>(n)
所以这本身并不是不好的做法。不好的做法是让原始指针完全悬空,如果有一个代码路径既不删除它也不将其传输到智能指针,那么它可能会泄漏。
你应该从
开始unique_ptr<node> n(new node);
并通过移动它来转移所有权
head = std::move(n);
关于c++ - 类型转换指向 unique_ptr 的普通指针是一种不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30370730/