What is the use of smart pointer? Where should be it used? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

What is the use of smart pointer? Where should be it used?

11th Oct 2017, 10:40 PM
Vijay
Vijay - avatar
3 Answers
+ 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
12th Oct 2017, 12:57 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 2
except auto_ptr is deprecated and shouldn't be used anymore, but you can use all the others freely
12th Oct 2017, 6:06 AM
‎ɐısıօլɐ
‎ɐısıօլɐ - avatar
+ 1
if you want create unlimited array or send array to function
11th Oct 2017, 11:24 PM
Hamid Reza Gholami Boroujeni
Hamid Reza Gholami Boroujeni - avatar