假设我有一个这样的类:
class Node {
public:
Node(Node* parent = 0) : mParent(parent) {}
virtual ~Node() {
for(auto p : mChildren) delete p;
}
// Takes ownership
void addChild(Node* n);
// Returns object with ownership
Node* firstChild() const;
// Does not take ownership
void setParent(Node* n) { mParent = n; }
// Returns parent, does not transfer ownership
Node* parent() const { return mParent; }
private:
list<Node*> mChildren;
Node* mParent;
};
我现在想使用智能指针和/或右值引用来表明所有权何时转移。
我的第一个猜测是将mChildren
更改为包含unique_ptr
,并相应地调整函数签名。
// Takes ownership
void addChild(unique_ptr<Node> n);
// Returns object with ownership
unique_ptr<Node>& firstChild() const;
// Does not take ownership
void setParent(Node* n) { mParent = n; }
// Returns parent, does not transfer ownership
Node* parent() const { return mParent; }
现在,当我需要将
Node::firstChild()
的结果传递给一些观察它但不拥有它的函数时,这可能会有些棘手,因为我需要在unique_ptr
上显式调用.get()
,而根据我的理解,这并不推荐。有没有更好、更推荐的方法来使用
unique_ptr
表示所有权,而无需使用.get()
和传递裸指针?
parent()
返回一个非唯一指针,这意味着我必须为原始指针和唯一指针重载每个函数。 - Symaxion