Typecasting指向unique_ptr的正常指针是一种不好的做法吗?

Car*_*nta 0 c++ c++11

我使用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
  }
}
Run Code Online (Sandbox Code Playgroud)

我听说这是一个不好的做法,如果有,那么有人可以告诉我为什么吗?有关正确做法的建议和提示也将受到赞赏.

Mik*_*our 5

虽然演员语法有点奇怪,但它与传统语法完全相同

unique_ptr<node>(n)
Run Code Online (Sandbox Code Playgroud)

所以本身并不是不好的做法.什么是不好的做法是让原始指针悬而未决,如果有一个代码路径没有删除它或将其转移到智能指针,它可能会泄漏.

你应该从头开始

unique_ptr<node> n(new node);
Run Code Online (Sandbox Code Playgroud)

并从中转移所有权

head = std::move(n);
Run Code Online (Sandbox Code Playgroud)

  • @CarloBrew:你应该,是的.然后,您可以确保它不会泄漏,而无需跟踪所有代码路径以确保. (2认同)