我使用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);

10-05 20:08