smart pointers

I have a question if I'm using pointers in a function
 
Node* current = &this->head;

can I rewrite it as a smart pointer instead for example
 
std::unique_ptr<Node> current = &this->head;
Not like that.

If you want a smart pointer to take ownership of an object, you must use the reset class member ( http://www.cplusplus.com/reference/memory/unique_ptr/reset/ ):

1
2
  std::unique_ptr<int> current ; 
  current.reset(&this->head);


This is dangerous, though. What if that pointer isn't on the heap? If you want to use smart pointers, use them right from the start. Whatever call to new created that Node object needs to be replaced with make_unique; https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique


head is a unique pointer already is that what you mean by using it from the start? if I leave current as a regular pointer would it get destroyed since head is a unique pointer after it passes out of scope of the function?
Last edited on
is that what you mean by using it from the start?


I mean you should never write new and you should never have a Node*
Topic archived. No new replies allowed.