jeudi 21 mai 2015

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

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 it is then can someone tell me why is it a bad practice? suggestions and tips for proper practices will also be surely appreciated. Thanks

Aucun commentaire:

Enregistrer un commentaire