Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pros and cons of smart pointers

Tags:

I came to know that smart pointer is used for resource management and supports RAII.

But what are the corner cases in which smart pointer doesn't seem smart and things to be kept in mind while using it ?

like image 842
Ashish Avatar asked Dec 15 '09 07:12

Ashish


People also ask

What are the advantages of using smart pointers?

One of the advantages of smart pointers is, that they ensure due to RAII, that the actual object is deleted. When using a raw pointer, you need to have a delete for every possible exit point, and still an exception will lead to a memory leak. Smart pointers will also free the memory if an exception occurs.

Are smart pointers worth it?

Smart pointers should be preferred over raw pointers. If you feel you need to use pointers (first consider if you really do), you would normally want to use a smart pointer as this can alleviate many of the problems with raw pointers, mainly forgetting to delete the object and leaking memory.

Why are smart pointers better than raw pointers?

Smart pointers are class objects that behave like raw pointers but manage objects that are new and when or whether to delete them— smart pointers automatically delete the managed object at the appropriate time.

What are the constraints of using smart pointers with functions?

Smart pointers don't help against loops in graph-like structures. For example, object A holds a smart pointer to object B and object B - back to object A. If you release all pointers to both A and B before disconnection A from B (or B from A) both A and B will hold each other and form a happy memory leak.


1 Answers

Smart pointers don't help against loops in graph-like structures.

For example, object A holds a smart pointer to object B and object B - back to object A. If you release all pointers to both A and B before disconnection A from B (or B from A) both A and B will hold each other and form a happy memory leak.

Garbage collection could help against that - it could see that both object are unreachable and free them.

like image 194
sharptooth Avatar answered Oct 13 '22 21:10

sharptooth