学习RAII 成语(Resource Acquisition Is Initialization)!参见例如关于 RAII 的 Wikipedia 文章。
RAII 只是一般的想法。它用于例如 C++ 标准库std::unique_ptr
或std::shared_ptr
模板类中。
RAII 成语的非常简短的解释:
基本上,它是try..finally
在其他一些语言中发现的块的 C++ 版本。RAII 成语可以说更灵活。
它是这样工作的:
重要的一点是,如何退出范围并不重要。即使抛出异常,仍然退出作用域并且仍然调用包装对象的析构函数。
非常粗略的例子:
// BEWARE: this is NOT a good implementation at all, but is supposed to
// give you a general idea of how RAII is supposed to work:
template <typename T>
class wrapper_around
{
public:
wrapper_around(T value)
: _value(value)
{ }
T operator *()
{
return _value;
}
virtual ~wrapper_around()
{
delete _value; // <-- NOTE: this is incorrect in this particular case;
// if T is an array type, delete[] ought to be used
}
private:
T _value;
};
// ...
{
wrapper_around<char*> heap( new char[50] );
// ... do something ...
// no matter how the { } scope in which heap is defined is exited,
// if heap has a destructor, it will get called when the scope is left.
// Therefore, delegate the responsibility of managing your allocated
// memory to the `wrapper_around` template class.
// there are already existing implementations that are much better
// than the above, e.g. `std::unique_ptr` and `std::shared_ptr`!
}