为什么 std::enable_shared_from_this 不使用可变的 std::weak_ptr?

Why doesn't std::enable_shared_from_this use a mutable std::weak_ptr?

我知道大多数标准库实现选择通过在基 class 中存储 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 没有实现?

为了阐明下面的答案:它是用标记为 mutablestd::weak_ptr 实现的,但这只允许 std::weak_ptr 被变异,而不是让我们交出一个非-const 给别人。

These both fail to compile:

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 函数中 thisconst.