简体   繁体   中英

Is smart pointer a good practice of 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?

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.

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