繁体   English   中英

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

[英]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函数中, thisconst

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM