C++程序的设计机制3: RAII机制(二)

2014-11-24 13:01:22 · 作者: · 浏览: 1
=(const RAII& other);
};
我们在具体使用把保护的指针Someresource放在RAII中:

class Example {
RAII p_;
RAII p2_;
public:
Example() :
p_(new SomeResource()),
p2_(new SomeResource()) {}

Example(const Example& other)
: p_(new SomeResource(*other.p_)),
p2_(new SomeResource(*other.p2_)) {}

Example& operator=(const Example& other) {
// Self assignment
if (this==&other)
return *this;

*p_=*other.p_;
*p2_=*other.p2_;
return *this;
}

~Example() {
std::cout << "Deleting Example, freeing SomeResource! ";
}
};
现在即使p_成功而p2_失败,那么在Stack winding时也会调用RAII的析构函数保证了p_指向的Someresource被析构。这种方法较之例1中需要实现被组合的指针类型相应的接口不同,这里不需要对接口进行封装。当然,在例1中,你也可以提供一个getPointer的函数直接将句柄提供出来。

其实在Example中,已经不需要析构函数了,因为RAII类会帮它照顾好这一切的。这有点像auto_ptr,本文并不打算深入讨论智能指针这个话题。

3)锁操作

/*
* ================================================================================

*
&