[英]How to avoid circular references with member callbacks & shared_ptr?
[英]Member objects, references and shared_ptr
因此,我发现自己经常这样做,并且想知道这是否正确(这可能无法编译-我正在用手机编写此代码):
class Shared
{
private:
int _x;
public:
void X(int newValue) { _x = newValue; }
int X() { return _x; }
Shared(void) : _x(0)
{
}
};
class Owner
{
private:
shared_ptr<Shared> _shared;
public:
const Shared& Shared() const
{
return *_shared;
}
void Shared(const Shared& newValue)
{
_shared.reset(&newValue);
}
void DoSomethingWithShared()
{
/// yeah, this could be cleaner, not the point!
_shared.X(_shared.X() + 1);
}
};
void CreateStuff(Owner& a, Owner &b)
{
Shared s;
a.Shared(s);
b.Shared(s);
}
int main(int argc, char *argv[])
{
Owner a;
Owner b;
CreateStuff(a,b);
a.DoSomethingWithShared();
b.DoSomethingWithShared();
///...
/// "Shared" instance created in CreateStuff() hopefully lives until here...
}
这个想法是Owner
多个实例需要类型为Shared
的共享资源。
CreateStuff()
是错误吗? (即s
超出范围,使a
和b
带有指向被破坏对象的无效指针?(我是否以回旋方式返回临时地址)?)
我没有看到其他范围/ GC问题吗?
有没有更简单的方法可以做到这一点?
CreateStuff
绝对是错误的。 您(最终)将一个指向局部变量的指针传递给shared_ptr
,该变量的寿命超过了该变量。 一旦超出范围,这些_shared
内将有两个悬空指针。
由于您正在使用智能指针,为什么不在堆栈上动态分配该Shared
,而让智能指针担心在完成后将其删除呢?
void CreateStuff(Owner& a, Owner &b)
{
std::shared_ptr<Shared> s(new Shared);
a.Shared(s); // have that Shared() modified to take the shared_ptr,
b.Shared(s); // of course
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.