make_unique and delete?

Hello,

I read that we should prefer make_unique over raw pointers. However, I am not sure if we need to delete it or make it nullptr after its usage.

For example:

1
2
  auto ptr_rect = std::make_unique<Rectangle>(r);
  ptr_rect.reset();


Is it necessary to include the unique_ptr::reset after using the make_unique? Or make_unique will do everything to avoid a leak?

Also, I read in herbsutter.com that:

As with make_shared, there are two main cases where you can’t use make_unique to create an object that you know will be owned (at least initially) by a unique_ptr: if you need a custom deleter, or if you are adopting a raw pointer.


When would we need a custom deleter? Any beginner friendly example?

Thanks! :)
You do not need to delete. The unique pointer is a smart pointer. When it goes out of scope, it will call delete on the object it is pointing to.

You should not call reset on it unless you have a really good reason. I mean this; you need a good reason. One possible reason (that still isn't a great reason) would be that you have something else for it to point to, and you're happy for what it's pointing to at the moment to be destroyed; calling reset on it and making it point at nothing is generally a bad reason. The point of them is that you tie the lifetime of the object to the pointer, safe in the knowledge that it will be properly tidied up. When the pointer is destructed, what it points to is deleted, every time.

You do not need to make it nullptr. It's a smart pointer that handles all that sort of thing for you. If you do all this manual memory management yourself, what's the point of having it?

You'd need a custom deleter if the object you're pointing at needs more than just plain "delete" when you're done with it. Maybe it's some class with a "deinitialise" of some kind function that needs to be called before it is deleted (although that'd be a pretty badly designed class). You'd write a custom deleter function. Another example; an object that you don't actually get from new, but you get from something else, and you don't release using delete - here's an excellent example using SDL2 ; http://swarminglogic.com/jotting/2015_05_smartwrappers.

In that example, IMG_Load is a function that provides a pointer to an image object, and it must be cleared up when you're done with it by SDL_FreeSurface. Nowhere do you call malloc/new, or free/delete. As that page shows, a unique pointer can be given a custom deleter so that it calls the right function for you when the unique pointer is destructed.
Last edited on
Thank you Repeater!

Now it is crystal clear to me! :)
Topic archived. No new replies allowed.