【发布时间】:2016-07-07 16:09:49
【问题描述】:
我有一个容器类:
class Container {
public:
MyItem* getItem() { return mItem.get(); }
private:
std::auto_ptr<MyItem> mItem;
};
我正在尝试编写一个initializeContainer() 方法,我使用Container.getItem() 来设置mItem。以下是一些可能的方法,我在 cmets 中对它们表示怀疑:
void initialize(Conatiner& container) {
MyItem item;
container.getItem() = &item; // Wrong, item gets destroyed at the end of the function
container.getItem() = new MyItem();
// This approach is filling my needs so far, but that doesn't necessarily
// mean it's correct.
// In particular, I'm not sure this approach properly removes the original item.
// Here I try to use placement new to reuse the memory pointed to by container.getitem
if (container.getItem()) {
MyItem* pItem = container.getItem();
pItem->~MyItem();
pItem = new (pItem) MyItem();
} // but if the pointer is null, I don't have any memory to reassign!
}
有没有一种惯用的方法来通过指针处理填充字段?我无权访问 C++11 功能或 Boost 等外部库。我也不允许更改Container的界面。
【问题讨论】:
-
请停止使用
std::auto_ptr,在某些情况下它可能是危险的,自 C++11 起已弃用它以支持std::unique_ptr,并且std::auto_ptr将从 C+ 中删除+17 标准。 -
如果您只允许通过公共函数进行修改,为什么还要保持私有?无论如何,
*container.getItem() = MyItem();呢? -
另请注意,
getItem返回存储的指针按值,因此在左侧使用getItem进行任何赋值都将不起作用。可能做例如*container.getItem() = MyItem()应该可以工作。它确实绕过了智能指针的整个“所有权”模型。 -
就我而言,方法名称
getItem与获取Item相关联,而不是与它的修改相关联。为什么不写setItem来更改Item? -
如何使用移动语义:
std::unique_ptr<MyItem> p2(new MyItem); p1 = std::move(p2);