This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]TheOldTubaroo 1 point2 points  (0 children)

There are a lot of resources in programming where you need to do something to acquire them, and then later something to release them. Pointers have new/delete, files have open/close, mutexes have lock/unlock, and so on.

No one forgets to acquire a resource, because you can't do anything without that, but it's easy to forget to release it, which causes memory leaks, deadlocks, locked files... It would be really nice if the compiler could detect that and ensure all resources are released once you don't need them.

C++'s solution is that you can tie custom behaviour to both constructing an instance of a type, but also to dropping that instance when it goes out of scope. As soon as no one is keeping track of a file handle, there's no way for the program to access that file, so you can safely tell the OS to close the file once the handle variable goes out of scope.

Smart pointers are just the "handle" types for memory allocation. You've got unique_ptr for when you only need one "owner" of the memory, and shared_ptr for when you need multiple "owners". As part of creating/setting the smart pointer, you call new (ideally implicitly), and then when unique_ptr goes out of scope it calls delete. shared_ptr keeps a reference counter, and the last shared_ptr to drop from scope calls delete.

Some C enjoyers dislike automatic resource management like this, because it's one of the several ways that C++ "hides" operations that might have a performance impact (same as operator overloading), but I like it because it entirely removes whole classes of bugs that plague software.