4

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?

choxsword
  • 3,187
  • 18
  • 44
  • 2
    RRID is what exactly? – john Feb 10 '18 at 10:18
  • @john _Resource Release Is Destruction_ – Felix Glas Feb 10 '18 at 10:19
  • 3
    shared_ptr is definitely RAII, but of course, a shared pointer represents shared ownership. RRID is just a better name for the standard term RAII. – Erik Alapää Feb 10 '18 at 10:19
  • 3
    Using the term "STL" like that suggests that your colleague may not be very precise in his definitions. – Sneftel Feb 10 '18 at 10:32
  • @ErikAlapää Is that true?I've heard that **RAII is a superset of RRID**.I've tried to find something of **RRID** in stackoverflow,but there are few discussions about that. – choxsword Feb 10 '18 at 10:33
  • Perhaps all your colleague really wanted to say is that "RAII" is a bad name for the idiom because it puts the emphasis on construction when the defining part is definitely destruction. But that's old news; everyone knows what "RAII" really means, and no one takes it that literally. – Christian Hackl Feb 10 '18 at 10:51
  • @bigxiao Yes, true. I am not sure, but I even think Stroustrup himself (or maybe it was ISO chair Herb Sutter...) said that RRID would have been a better name. – Erik Alapää Feb 10 '18 at 10:54

1 Answers1

6

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.

Felix Glas
  • 15,065
  • 7
  • 53
  • 82