[英]Member objects, references and shared_ptr
So, I've found myself doing this a lot, and wonder if it's correct practice (this probably won't compile - I'm writing this on my phone): 因此,我发现自己经常这样做,并且想知道这是否正确(这可能无法编译-我正在用手机编写此代码):
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...
}
The idea is that multiple instances of Owner
need a shared resource of type Shared
. 这个想法是
Owner
多个实例需要类型为Shared
的共享资源。
Is CreateStuff()
an error? CreateStuff()
是错误吗? (ie, does s
go out of scope, leaving a
and b
with invalid pointers to a destroyed object? (Am I returning the address of a temporary in a roundabout way?) (即
s
超出范围,使a
和b
带有指向被破坏对象的无效指针?(我是否以回旋方式返回临时地址)?)
Are there any other scope/GC issues I'm not seeing? 我没有看到其他范围/ GC问题吗?
Is there an easier way to do this? 有没有更简单的方法可以做到这一点?
CreateStuff
is definitively wrong. CreateStuff
绝对是错误的。 You're (eventually) passing a pointer to a local variable into the shared_ptr
s, which outlive that variable. 您(最终)将一个指向局部变量的指针传递给
shared_ptr
,该变量的寿命超过了该变量。 Once it goes out of scope, you'll have two dangling pointers inside those _shared
s. 一旦超出范围,这些
_shared
内将有两个悬空指针。
Since you're using smart pointers, why not dynamically allocate that Shared
on the heap, and let the smart pointers worry about deleting it when they're done? 由于您正在使用智能指针,为什么不在堆栈上动态分配该
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.