简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM