假设我们和一个投资(例如,股票,债券等)模型库一起工作,各种各样的投资形式从一个根类 Investment 派生出来: class Investment { ... }; // root class of hierarchy of investment types
进一步假设这个库使用了通过一个 factory 函数为我们提供特定 Investment 对象的方法: Investment* createInvestment(); // return ptr to dynamically allocated // object in the Investment hierarchy; // the caller must delete it (parameters omitted for simplicity)
通过注释指出,当 createInvestment 函数返回的对象不再使用时,由 createInvestment 的调用者负责删除它。那么,请考虑,写一个函数 f 来履行以下职责: void f() { Investment *pInv = createInvestment(); // call factory function ... // use pInv delete pInv; // release object }