我對C++和智能指針的使用比較新,因爲我主要使用C#。我在這裏經歷了很多關於unique_ptrs正確用法的問題,我想我明白,智能指針都是關於所有權的,並且當超出範圍時將負責刪除指針所持有的內存。正確使用unique_ptr父/子關係
那就是說,它下面的例子正確嗎?家長將永遠是孩子的主人,並管理孩子的一生。但是,如果另一個班級需要照顧孩子,並且生活總是比孩子少,那麼這個班級可以爲孩子保留一個原始指針嗎?
class ChildTypeA;
class ChildTypeB;
class Parent
{
public:
ChildTypeA* createChildA()
{
ChildTypeA *aPtr = new ChildTypeA(/* pass this to constructor */);
typeAChildren.push_back(std::unique_ptr<ChildTypeA>(aPtr));
return aPtr;
}
ChildTypeB* createChildB()
{
ChildTypeB *aPtr = new ChildTypeB(/* pass this to constructor */);
typeBChildren.push_back(std::unique_ptr<ChildTypeB>(aPtr));
return aPtr;
}
void somethingCalledByChildA()
{}
void somethingCalledByChildB()
{}
private:
std::vector<std::unique_ptr<ChildTypeA>> typeAChildren;
std::vector<std::unique_ptr<ChildTypeB>> typeBChildren;
};
class ChildTypeA
{
public:
ChildTypeA() {} // parameterless constructor purely for single file example
ChildTypeA(Parent *parent) : owningParent(parent)
{}
void notifyParentOfSomethingA()
{
owningParent->somethingCalledByChildA();
}
void doSomethingOnThisChild()
{}
private:
Parent *owningParent;
};
class ChildTypeB
{
public:
ChildTypeB() {} // parameterless constructor purely for single file example
ChildTypeB(Parent *parent) : owningParent(parent)
{}
void notifyParentOfSomethingB()
{
owningParent->somethingCalledByChildB();
}
private:
Parent *owningParent;
};
class SomeOtherClassThatWantsAChildAAndWillAlwaysLiveShorterThanChildA
{
public:
SomeOtherClassThatWantsAChildAAndWillAlwaysLiveShorterThanChildA(ChildTypeA *child) : childNotOwnedByMe(child)
{}
void doSomething()
{
childNotOwnedByMe->doSomethingOnThisChild();
}
private:
ChildTypeA * childNotOwnedByMe;
};
那麼接下來代碼某處會做這樣的事情:
ChildTypeA *a = someInstanceOfParent->createChildA();
auto x = new SomeOtherClassThatWantsAChildAAndWillAlwaysLiveShorterThanChildA(a);
您可能想考慮使用引用而不是指針。 –
如果你只是觀察一些東西,原始指針就可以完成這項工作。這包括持有原始父指針的孩子。 – yngccc
我確實考慮過將Parent引用傳遞給ChildA/B,但在另一篇文章中已經閱讀過引用類成員可能存在問題的情況,尤其是如果我需要更改ownParent。 – RobertW