繁体   English   中英

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

[英]operator -> or ->* applied to "const std::weak_ptr" instead of to a pointer typeC/C++

在 lambda function 中,我试图使用 weak_ptr 来访问所有成员 function 和变量。 收到此错误
运算符 -> 或 ->应用于“const std::weak_ptr”而不是指针类型C/C++ *

std::weak_ptr<T>按设计安全地指代可能存在或不存在的 object。 它不提供operator->operator* ,因为您必须确保 object 仍然存在,然后才能尝试访问它。

要访问由std::weak_ptr引用的 object,您首先调用lock() ,它返回std::shared_ptr 然后,您需要检查std::shared_ptr是否引用了 object。 如果是这样,那么 object 是可以安全访问的,并且在返回的指针被销毁之前不会被删除(因为它仍然存在一个std::shared_ptr )。 如果不是,则std::weak_ptr指的是您无法再访问的已损坏 object 。

示例

#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();
    }
}

暂无
暂无

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

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