【发布时间】:2012-03-11 05:33:33
【问题描述】:
我在一个大型系统中遇到了一个不寻常的问题,由于各种原因,我可能不得不使用这样的构造:
class Item
{
int mID;
int mID2;
...
int mIDn;
public:
Item();
Item(const Item& Other);
Item& operator=(const Item &Other);
};
class ItemExtension : public Item
{
// some data
public:
ItemExtension(const Item &Other) : Item(Other) {}
ItemExtension(const ItemExtension &Other);
ItemExtension& operator=(const ItemExtension& Other);
};
// client code
Item *Myitem = ItemList.ReleaseItem(index); // ownership transferred and an Item is removed from a list
std::auto_ptr<ItemExtension> ItemExt(new ItemExtension(*MyItem));
ItemExtList.push_back(ItemExt.release()); // store in std::vector and take ownership
我意识到这里存在设计缺陷,例如指针所有权的混乱转移,但是如果您需要复制的数据主要包含在基类,但您需要仅在派生类中支持的特定功能?非常感谢。
【问题讨论】:
-
它不是复制构造函数。它只是另一个构造函数。不要害臊。
-
@KerrekSB 我认为他只说“复制构造函数 like”,不是吗?
-
你应该小心这个。请记住,引用会触发多态性。因此,如果您有一个具有派生类类型但通过基类引用或指针引用的对象,那么接受它的构造函数就是接受基类引用的构造函数。这对您或呼叫者来说可能是违反直觉的。
标签: c++ inheritance copy-constructor