Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between RAII and smart pointers in C++

The difference between those two is not clear for me, yet. What I have read about them have been very massive and complex (as the C++ is). For example, this one which belongs to years ago and from WikiPedia as well. Probably the issue is complex in itself.

What I think about them is that, RAII is a mechanism that we use it for smart pointers, but I'm not sure about this. I need a simple and straightforward answer.

Would you please explain it in a simple language with a small sample code? Please bear in mind that I'm at a low level in C++.

like image 401
Franky Avatar asked Dec 06 '22 18:12

Franky


1 Answers

RAII is the idea of using C++'s automatic call of a destructor, to release resources acquired in a constructor.

The acronym indicates that only vaguely, Resource Acquisition Is Initialization.

A smart pointer is a class that overloads at least operator-> and the dereference operator* to enable use with pointer notation. Typically a smart pointer will use RAII techniques to automatically deallocate memory. But it can do other things. It is however implicit that a smart pointer deals somehow with ”ownership” of a contained raw pointer. For example, a simple iterator class overloads operator-> and operator* but is not regarded as a smart pointer.

like image 53
Cheers and hth. - Alf Avatar answered Dec 31 '22 09:12

Cheers and hth. - Alf