c++ - 类型转换指向 unique_ptr 的普通指针是一种不好的做法吗?

标签 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
  }
}

我听说这是一种不好的做法,如果是的话,有人能告诉我为什么吗?对于正确做法的建议和技巧也将不胜感激。

最佳答案

虽然强制转换语法有点奇怪,但它完全等同于更常规的语法

unique_ptr<node>(n)

所以这本身并不是不好的做法。不好的做法是让原始指针完全悬空,如果有一个代码路径既不删除它也不将其传输到智能指针,那么它可能会泄漏。

你应该从

开始
unique_ptr<node> n(new node);

并通过移动它来转移所有权

head = std::move(n);

关于c++ - 类型转换指向 unique_ptr 的普通指针是一种不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30370730/

相关文章:

c++ - 释放锁时的线程调度

c++ - typedef _W64 unsigned int UINT_PTR, *PUINT_PTR;

c++ - Hinnant 的 short_alloc 和对齐保证

c++ - 如何修复 -Wsubobject-linkage 警告?

C++ 在里面执行函数和 lambda

c++ - 如何正确使用 unordered_map C++

c++ - 将可变参数模板链接在一起

c++ - 如何在 C++ 中打印 int 的 ASCII 值?

C++ 对齐数组的未对齐属性

c++ - 卡尔曼滤波器没有给出正确的结果