在 C++ 中,容器(如數組)通常只能存儲單一類型的對象。若需存儲繼承自同一基類的不同派生類對象(如 Vehicle、RoadVehicle、Aircraft 等),直接存儲對象會導致對象切片,丟失派生類特有成員;存儲指針雖能利用多態,卻引入動態內存管理負擔與生命週期控制難題。
最早的方案是存儲基類指針(Vehicle* parking_lot[1000]),但面臨兩大問題:
parking_lot[p] = new Vehicle(*parking_lot[q]) 會導致切片)。在基類中引入純虛函數 virtual Vehicle* copy() const = 0,每個派生類實現為 return new Derived(*this)。配合虛析構函數 virtual ~Vehicle() {},即可實現運行時類型感知的深度復制。
class VehicleSurrogate {
public:
VehicleSurrogate() : vp(0) {}
VehicleSurrogate(const Vehicle& v) : vp(v.copy()) {}
~VehicleSurrogate() { delete vp; } // delete 空指針安全
VehicleSurrogate(const VehicleSurrogate& v)
: vp(v.vp ? v.vp->copy() : 0) {}
VehicleSurrogate& operator=(const VehicleSurrogate& v) {
if (this != &v) {
delete vp;
vp = v.vp ? v.vp->copy() : 0;
}
return *this;
}
private:
Vehicle* vp;
};
const Vehicle&,利用多態調用正確的 copy() 創建副本vp=0 的空代理,支持數組定義VehicleSurrogate parking_lot[1000]; Automobile x; parking_lot[num_vehicles++] = x; // 等價於 parking_lot[...] = VehicleSurrogate(x);
此時會創建 x 的副本並由代理對象管理,數組銷毀時自動清理所有副本。代理類將整個繼承體系「壓縮」為單一類型,兼具值語義與多態行為,是 C++ 中實現異構容器的經典模式。