- RAII This is a bad name for a simple but awesome concept. Better is the name Scope Bound Resource Management (SBRM). The idea is that often you happen to allocate resources at the begin of a block, and need to release it at the exit of a block. Exiting the block can happen by normal flow control, jumping out of it, and even by an exception. To cover all these cases, the code becomes more complicated and redundant.
RAII This is a strange name for a simple but awesome concept. Better is the name Scope Bound Resource Management (SBRM). The idea is that often you happen to allocate resources at the begin of a block, and need to release it at the exit of a block. Exiting the block can happen by normal flow control, jumping out of it, and even by an exception. To cover all these cases, the code becomes more complicated and redundant.
Just an example doing it without SBRM:
- unique_ptr is a smart pointer which owns an object exclusively. It's not in boost, but it will likely appear in the next C++ Standard. It's non-copyable but supports transfer-of-ownership. Some example code (next C++):
[**unique_ptr**][1]
is a smart pointer which owns an object exclusively. It's not in boost, but it will likely appear in the next C++ Standard. It's *non-copyable* but supports *transfer-of-ownership*. Some example code(next C++):unique_ptr<plot_src> p(new plotplot_src); // now, p owns
unique_ptr<plot_src> u(move(p)); // now, u owns, p owns nothing.
unique_ptr<plot_src> v(u); // error, trying to copy u
vector<unique_ptr<plot_src>> pv;
pv.emplace_back(new plot_src);
pv.emplace_back(new plot_src);
- scoped_ptr is a boost smart pointer which is neither copyable nor movable. It's the perfect thing to be used when you want to make sure pointers are deleted when going out of scope.
[**scoped_ptr**][2]
is a boost smart pointer which is neither copyable nor movable. It's the perfect thing to be used when you want to make sure pointers are deleted when going out of scope.- shared_ptr is for shared ownership. Therefor, it's both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed. Some real world example of one of my projects:
[**shared_ptr**][3]
is for shared ownership. Therefor, it's both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed. Some real world example of one of my projects:shared_ptr<plot_src> p(new plotplot_src(&fx));
plot1->add(p)->setColor("#00FF00");
plot2->add(p)->setColor("#FF0000");
// if p now goes out of scope, the src won't be freed, as both plot1 and
// plot2 both still have references.