我对 C++ 和智能指针比较陌生,因为我主要使用 C#。我在这里遇到了很多关于正确使用 unique_ptrs 的问题,我想我理解智能指针都是关于所有权的,当指针超出范围时,谁将负责删除指针所持有的内存。
也就是说,下面的例子正确吗?父母永远是孩子的主人,管理孩子的一生。但是,如果另一个班级需要拥有一个孩子,并且总是比孩子活得少,那么该班级是否可以持有指向孩子的原始指针?
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);