![](/img/trans.png)
[英]Try to understand std::enable_shared_from_this<T> but cause a bad_weak_ptr using it
[英]Why doesn't std::enable_shared_from_this use a mutable std::weak_ptr?
我知道大多数 std 库实现选择通过在基类中存储std::weak_ptr
来实现std::enable_shared_from_this
。 这导致以下情况:
#include <memory>
class Foo : public std::enable_shared_from_this<Foo>
{
public:
std::shared_ptr<Foo> GetSharedBar() const
{
// returns shared_ptr<const Foo> instead of std::shared_ptr<Foo>
return shared_from_this();
// Error in VC++2019 due to mismatch.
}
};
我似乎很清楚,尽管需要更新引用计数,但shared_from_this()
实际上并没有改变目标对象。 这似乎是可变的理想用途,因此可以将shared_from_this()
标记为相对于派生对象的const
。
为什么不使用mutable
实现?
为了阐明下面的答案:它与实现std::weak_ptr
标记mutable
,但只允许std::weak_ptr
发生突变,而不是我们的手断非const
给别人。
class Foo : public std::enable_shared_from_this<Foo>
{
public:
std::shared_ptr<Foo> GetSharedBar() const
{
// error: could not convert from 'shared_ptr<const Foo>' to 'shared_ptr<Foo>'
return shared_from_this();
}
};
class Bla
{
public:
Bla* getThis() const
{
// error: invalid conversion from 'const Bla*' to 'Bla*'
return this;
}
};
但是如果您从函数中删除const
,它们都可以工作。 问题是在const
成员函数中, this
指针是一个const
指针。
再举一个例子,看看这个:
class kluf
{
const std::string* k;
std::string* getK()
{
// error: invalid conversion from 'const string*' to 'std::string*'
return k;
}
};
很明显,您不能将const
成员交给处于非const
状态的其他人。 这也适用于this
指针,在const
函数中, this
是const
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.