Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is smart pointer a good practice of RAII?

Tags:

c++

raii

To start with, here is a discussion of RAII&Smart Pointer.
I've always thought that Smart Pointer like shared_ptr is a good practice of RAII because it gets the heap memory resource at constructor like

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

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

"smart pointer is not what i thought to be RAII. The only thing that can strictly be called as RAII in the STL is std::lock_guard, the others are nothing more than RRID. "

So did i get something wrong? Or what my collegue said actually made non-sense?

like image 230
scottxiao Avatar asked Oct 20 '25 13:10

scottxiao


1 Answers

From cppreference:

Resource Acquisition Is Initialization or RAII, is a C++ programming technique which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the lifetime of an object.

std::shared_ptr is definitely RAII as it aquires a resource and binds its lifetime to its own, thus taking over the responsibility of releasing/destructing the resource. This is the core principle of RAII.

The term RRID (Resource Release Is Destruction) is rarely seen and its meaning seems to be somewhat ambiguous. Mostly it is used with the same meaning as RAII.

IMHO many discussions revolving around variants of RAII deem from interpreting the meaning of the term too exactly. RAII is meant to represent a concept of object life-time management.

like image 129
Felix Glas Avatar answered Oct 23 '25 03:10

Felix Glas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!