c++ - 如何正确使用 std::shared_from_this 或绕过它?

标签 c++ memory-management

C++ 专家的问题:我有一个库函数需要 shared_ptr<T>我想在 T 中调用此函数.我知道 share_from_this 是正确的方法,但我无法理解它(以及如何正确使用它)。

我想出了一个技巧,我想知道它是否安全(无 UB)。如果不是,你能解释一下如何使用 share_from_this 吗?就我而言?

#include <memory>

template<class T>
void library_function(std::shared_ptr<T>)
{}

struct A {
    std::shared_ptr<A> share()
    {
        return std::shared_ptr<A>(this, [](A*){});
    }

    void operator()()
    {
        library_function(share());
    }
};


int main()
{
    A a;
    a();
}

最佳答案

首先,你要的对象share_from_this需要是先前的共享对象并由 std::shared_ptr 管理。确保允许它的类需要公开继承自 std::enable_shared_from_this<A> .接下来,如果你想从中创建共享指针,你需要使用方法 shared_from_this() .

关于c++ - 如何正确使用 std::shared_from_this 或绕过它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41717034/

相关文章:

c++ - RSA算法——无法验证d

c++ - 如何强制指针在每次启动时不保持它们的值和顺序?

c++ - eclipse CDT : force indexing conditionally compiled code

ios - 核心数据导入 - 不释放内存

c++ - 在 C++ 中为数组分配新内存的问题

c++ - 使用 unordered_map 时的内存分配

c++ - 创建文件和内存管理

c++ - 为什么 MSVC 在寄存器中返回一个小结构时不必要地使用堆栈?

c++ - 如何计算存储在 map 中的 vector 中的元素数量

c++ - boost::interprocess -- std::string 与 std::vector