【发布时间】:2014-03-28 18:36:43
【问题描述】:
所以我有一些代码:
class Thing
{
public:
Thing() = default;
};
class DbOfThings
{
public:
DbOfThings() = default;
std::weak_ptr<Thing> GetEntry(int someKey) const
{
// returns a weak_ptr from mThings, or null if a Thing
// that has someKey was not found
return std::weak_ptr<Thing>(nullptr);
}
private
// Idea is that this object owns these things, but other objects can grab a thing from here - but the thing can be killed off at any time
std::vector<std::share_ptr<Thing>> mThings;
但这无法编译:
没有已知的参数 1 从 'std::nullptr_t' 到 'const 的转换 std::weak_ptr&'
为什么?我让其他物体抓住另一个错误拥有的东西的方法是错误的吗?对我来说,这似乎是 weak_ptr 的一个有效用例。我怎样才能做到这一点?
【问题讨论】:
-
好像没有这样的构造函数,但是你可以使用默认的:
return {}; -
如果向量是唯一拥有对象的东西,为什么要使用
shared_ptr而不是unique_ptr? (或者你不能为unique_ptr拥有的对象创建weak_ptrs,即使弱指针不会导致指向的对象的所有权发生变化?) -
...哦,我明白了。因为
shared_ptr可以将weak_ptr作为构造函数,所以允许指向唯一指针拥有的对象的弱指针将需要杀死唯一指针,尽管shared_ptr有一个unique_ptr构造函数,它只是间接地这样做可能会有奇怪的效果。 -
@jab 更根本的是,
.lock()是您访问weak_ptr的方式,如果它不能延长指向对象的生命周期,那有什么好处? -
是的,奇怪的是unique_ptr 没有weak_ptr - 当你想传递它但不改变所有者时
标签: c++ c++11 shared-ptr