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

How are smart pointers different from regular pointers?


Asked by Sky Hansen on Dec 09, 2021 FAQ



The characteristic that distinguishes a smart pointer from an ordinary struct is that smart pointers implement the Deref and Drop traits. The Deref trait allows an instance of the smart pointer struct to behave like a reference so you can write code that works with either references or smart pointers.
Subsequently,
Sydius outlined the types fairly well: Normal pointers are just that - they point to some thing in memory somewhere. Smart pointers are a blanket term that cover many types; I'll assume you meant scoped pointer which uses the RAII pattern. Shared pointers is a stack-allocated object that wraps a pointer so that you don't have to know who owns it.
Thereof, As shown in the example, a smart pointer is a class template that you declare on the stack, and initialize by using a raw pointer that points to a heap-allocated object. After the smart pointer is initialized, it owns the raw pointer. This means that the smart pointer is responsible for deleting the memory that the raw pointer specifies.
Similarly,
So in C++ 11, it introduces smart pointers that automatically manage memory and they will deallocate the object when they are not in use when the pointer is going out of scope automatically it’ll deallocate the memory. Consider the following simple C++ code with normal pointers.
Consequently,
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. Don’t forget to subscribe to the blog newsletter to get notified of future posts. You can also get updates following me on Google+, LinkedIn and Twitter.