C++ 中面向对象编程的一个颇具讽刺意味的地方是,不能使用对象支持面向对象编程,相反,必须使用指针或引用。例如,下面的代码段:
void get_prices(Item_base object, const Item_base *pointer, const Item_base &reference) { // which version of net_price is called is determined at run time cout << pointer->net_price(1) << endl; cout << reference.net_price(1) << endl; // always invokes Item_base::net_price cout << object.net_price(1) << endl; } 这里的object.net_price永远只能调用类Item_base中的函数,无法实现多态。于是,引入了句柄类这个概念。
其实句柄类也可以看作是另一种智能指针,它通过类B将类A的指针进行封装,当你需要调用类A指针的时候,
只需要调用类B的对象就可以了(调用的时候需要用到类B重载的解引用和箭头操作符)。
// use counted handle class for the Item_base hierarchy
class Sales_item {
public:
// default constructor: unbound handle
Sales_item(): p(0), use(new std::size_t(1)) { }
// attaches a handle to a copy of the Item_base object
Sales_item(const Item_base&);
// copy control members to manage the use count and pointers
Sales_item(const Sales_item &i):
p(i.p), use(i.use) { ++*use; }
~Sales_item() { decr_use(); }
Sales_item& operator=(const Sales_item&);
// member access operators
const Item_base *operator->() const { if (p) return p;
else throw std::logic_error("unbound Sales_item"); }
const Item_base &operator*() const { if (p) return *p;
else throw std::logic_error("unbound Sales_item"); }
private:
Item_base *p; // pointer to shared item
std::size_t *use; // pointer to shared use count
// called by both destructor and assignment operator to free pointers
void decr_use()
{ if (--*use == 0) { delete p; delete use; } }
};
赋值操作符比复制构造函数复杂一点:
// use-counted assignment operator; use is a pointer to a shared use count
Sales_item&
Sales_item::operator=(const Sales_item &rhs)
{
++*rhs.use;
decr_use();
p = rhs.p;
use = rhs.use;
return *this;
}未完待续