【发布时间】:2012-07-27 12:04:41
【问题描述】:
我目前正在尝试学习如何使用智能指针。然而,在做一些实验时,我发现了以下情况,我找不到令人满意的解决方案:
假设您有一个 A 类对象是 B 类对象(子对象)的父对象,但两者应该彼此认识:
class A;
class B;
class A
{
public:
void addChild(std::shared_ptr<B> child)
{
children->push_back(child);
// How to do pass the pointer correctly?
// child->setParent(this); // wrong
// ^^^^
}
private:
std::list<std::shared_ptr<B>> children;
};
class B
{
public:
setParent(std::shared_ptr<A> parent)
{
this->parent = parent;
};
private:
std::shared_ptr<A> parent;
};
问题是 A 类的对象如何将自己的 std::shared_ptr (this) 传递给它的子对象?
有 Boost 共享指针 (Getting a boost::shared_ptr for this) 的解决方案,但是如何使用 std:: 智能指针来处理这个问题?
【问题讨论】:
-
与任何其他工具一样,您必须在适当的时候使用它。对你正在做的事情使用智能指针是不是
-
类似提升。见here。
-
这是那个抽象级别的问题。你甚至都不知道“this”指向堆上的内存。
-
嗯,语言不会,但你会。只要您跟踪位置,就可以了。
标签: c++ this shared-ptr this-pointer