Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How are smart pointers different from raw pointers?


Asked by Madilynn Cherry on Dec 09, 2021 FAQ



Observe the output, In the case of the raw object pointer, the destructor of the Account class was not invoked. Whereas, in the case of smart object pointer, the destructor is automatically invoked as soon as the object goes out of the scope (i.e. object is automatically destroyed).
In fact,
Traditional pointers are now also known as raw pointers. I like to think of smart pointers as boxes that hold the dynamic data. In fact they are just classes that wrap the raw pointer in their bowels and overload the -> and * operators. Thanks to this trick a smart pointer offers the same syntax of a raw one.
Consequently, Which means there’s no noticeable difference between raw pointers and shared pointers. It’s fair to say that smart pointers do not create any real performance issue and that they can be safely used over classic raw pointers in pretty much any normal situation.
Moreover,
These smart pointers should always be used in preference to raw pointers in modern C++. They can help to prevent very common errors due to memory management and ownership which have plagued developers. These 3 types of pointer serve different purposes:
In respect to this,
There is no way to infer such information by simply looking at the return type. Smart pointers were born to fix the annoyances mentioned above. They basically provide automatic memory management: when a smart pointer is no longer in use, that is when it goes out of scope, the memory it points to is deallocated automatically.