简体   繁体   English

Typecast将普通指针指向unique_ptr是一种不好的做法吗?

[英]Is Typecasting a normal pointer to a unique_ptr a bad practice?

I implemented a singly linked list using unique_ptr with mix of normal pointers. 我使用unique_ptr和普通指针的混合实现了一个单链表。

I have this code: 我有以下代码:

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

I heard that it's a bad practice, if so then can someone tell me why? 我听说这是一个不好的做法,如果是这样,那么有人可以告诉我为什么吗? Suggestions and tips for proper practices will also be appreciated. 正确做法的建议和技巧也将不胜感激。

While the cast syntax is slightly strange, it's exactly equivalent to the more conventional 尽管强制转换语法有些奇怪,但它与传统的语法完全等效

unique_ptr<node>(n)

and so isn't itself bad practice. 因此,这本身也不是不好的做法。 What is bad practice is to have the raw pointer hanging around at all, with a danger that it might leak if there is a code path that doesn't either delete it or transfer it to a smart pointer. 不好的做法是完全使原始指针挂起,如果存在无法删除或将其传输到智能指针的代码路径,则可能会泄漏原始指针。

You should start with 你应该开始

unique_ptr<node> n(new node);

and transfer ownership by moving from it 并通过转移所有权来转移所有权

head = std::move(n);

In your case it may not be an issue but casting existing raw pointers to unique_ptrs is a bit of a bad practice mainly due to the semantics involved. 在您的情况下,这可能不是问题,但是将现有的原始指针强制转换为unique_ptrs有点不好,主要是因为所涉及的语义。 Unique_ptr will run a deleter when goes out of scope. 超出范围时,Unique_ptr将运行删除程序。

Consider the following 考虑以下

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

int main() {
    int i = 10;
    ptr_method(&i);
}

What happens to i when ptr_method returns ? ptr_method返回时, i ptr_method怎么办?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM