将普通指针类型转换为unique_ptr类型是一种不好的做法吗?

Is Typecasting a normal pointer to a unique_ptr a bad practice?

本文关键字:一种 类型转换 指针 unique 类型 ptr      更新时间:2023-10-16

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

在您的情况下,这可能不是问题,但是将现有的原始指针转换为unique_ptrs是一种不好的做法,主要是因为涉及到语义。当Unique_ptr超出作用域时,将运行delete。

考虑以下

int ptr_method(int * i) {
    auto a = (unique_ptr<int>)i;
    return *a.get();
}
int main() {
    int i = 10;
    ptr_method(&i);
}

ptr_method返回时,i会发生什么?