Is smart pointer good RAII practice?

To start, let's discuss RAII & Smart Pointer .
I always thought Smart Pointer as shared_ptra good RAII practice, because it gets the heap memory resource in the constructor, for example

shared_ptr<A> pA(new pA());

and can free memory at the right time through reference counting and its destructor.
However, this morning my colleague told me that:

smart pointer is not what I considered RAII . The only thing that can be strictly called RAII in STL is the std::lock_guardrest - no more than RRID . "

Am I also misunderstood something? Or what my colleague said doesn't actually make sense?

+4
source share
1 answer

From cppreference:

The acquisition of resources - this is initialization or RAII - is a C ++ programming method that binds the life cycle of a resource that must be obtained before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, connection with a database - everything that exists in limited sources) for the lifetime of the object.

std::shared_ptrdefinitely RAII, as it acquires the resource and binds its life to its own, taking responsibility for the release / destruction of the resource. This is the basic principle of RAII.

The term RRID (Release Release Is Destruction) is rarely found, and its meaning seems somewhat ambiguous. It is mainly used with the same value as RAII.

, RAII, , . RAII .

+5

Source: https://habr.com/ru/post/1693450/


All Articles