+ 3
What is the use of smart pointer? Where should be it used?
3 Respostas
+ 8
A smart pointer, unlike a normal pointer, handles memory management, checking of bounds and deallocation by itself. Thus, you need not care about using delete to destroy the pointer whenever you wish to store new data or you are done storing data in the program. It thus helps solved the problems of undefined references, dangling pointers, and memory leaks.
Basically, they are just a template class keeping a normal pointer, and overloading the * and -> operators for use like normal pointers, but maintain memory record and deallocate it implicitly via a destructor whenever the passed object goes out of scope.
There are 4 types of smart_pointers in C++, defined under <memory>:
auto_ptr, unique_ptr, weak_ptr, and shared_ptr.
The most commonly used is unique_ptr or weak_ptr.
For details on these types, read here:
www.cplusplus.com/reference/memory
+ 2
except auto_ptr is deprecated and shouldn't be used anymore, but you can use all the others freely
+ 1
if you want
create unlimited array or
send array to function