[英]operator -> or ->* applied to "const std::weak_ptr" instead of to a pointer typeC/C++
In lambda function, instead of this, I was trying to use weak_ptr to access all member function and variable.在 lambda function 中,我试图使用 weak_ptr 来访问所有成员 function 和变量。 Getting this Error
收到此错误
operator -> or -> applied to "const std::weak_ptr" instead of to a pointer typeC/C++ *运算符 -> 或 ->应用于“const std::weak_ptr”而不是指针类型C/C++ *
std::weak_ptr<T>
by design safely refers to an object which may or may not still exist. std::weak_ptr<T>
按设计安全地指代可能存在或不存在的 object。 It does not offer operator->
or operator*
since you have to make sure the object still exists before you can try to access it.它不提供
operator->
或operator*
,因为您必须确保 object 仍然存在,然后才能尝试访问它。
To access an object referred to by a std::weak_ptr
you first call lock()
which returns a std::shared_ptr
.要访问由
std::weak_ptr
引用的 object,您首先调用lock()
,它返回std::shared_ptr
。 Then, you need to check if that std::shared_ptr
refers to an object.然后,您需要检查
std::shared_ptr
是否引用了 object。 If it does, then the object is safe to access and won't be deleted until that returned pointer is destroyed (because there will still exist a std::shared_ptr
for it).如果是这样,那么 object 是可以安全访问的,并且在返回的指针被销毁之前不会被删除(因为它仍然存在一个
std::shared_ptr
)。 If it doesn't then the std::weak_ptr
was referring to a destroyed object which you can't access anymore.如果不是,则
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.