运算符 -> 或 ->* 应用于“const std::weak_ptr”而不是指针类型C/C++

The*_*ank 3 c++ weak-ptr

在 lambda 函数中,我尝试使用它weak_ptr来访问所有成员函数和变量,但出现此错误:

运算符 -> 或 ->* 应用于“const std::weak_ptr”而不是指针类型

Fra*_*eux 8

std::weak_ptr<T>通过设计安全地指的是一个可能仍然存在也可能不存在的对象。它不提供operator->or ,operator*因为您必须确保该对象仍然存在,然后才能尝试访问它。

要访问由std::weak_ptr返回. 然后,您需要检查 that 是否引用一个对象。如果是,则该对象可以安全访问,并且在返回的指针被销毁之前不会被删除(因为它仍然存在)。如果没有,则指的是您无法再访问的已销毁对象。lock()std::shared_ptrstd::shared_ptrstd::shared_ptrstd::weak_ptr

例子

#include <memory>

class foo 
{
public:
    void bar(){}
};

void test(std::weak_ptr<foo> ptr)
{
    // Get a shared_ptr
    auto lock = ptr.lock();

    // Check if the object still exists
    if(lock) 
    {
        // Still exists, safe to dereference
        lock->bar();
    }
}
Run Code Online (Sandbox Code Playgroud)