The difference between RAII and smart pointers in C++
Asked Answered
F

3

5

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++.

Fractionate answered 8/3, 2016 at 5:49 Comment(0)
B
12

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.

Banana answered 8/3, 2016 at 6:24 Comment(0)
I
9

They're complimentary concepts. RAII means that objects take care of their own resources automatically. Smart pointers are a way of accomplishing RAII for allocated memory.

Invest answered 8/3, 2016 at 5:59 Comment(1)
Thanks Mark. So what I'd think of them was correct! :)Fractionate
P
2

RAII is a technique:

Resource Acquisition Is Initialization or RAII, is a C++ programming technique[1][2] which binds the life cycle of a resource (allocated memory, thread of execution, open socket, open file, locked mutex, database connection—anything that exists in limited supply) to the lifetime of an object with automatic storage duration.

RAII's concept includes all the limited resources, while Smart points are expected to manage dynamically-allocated memory or any resource represented by a plain pointer, follow RAII.

Prairial answered 8/3, 2016 at 5:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.