简体   繁体   中英

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. Getting this Error
operator -> or -> applied to "const std::weak_ptr" instead of to a pointer typeC/C++ *

std::weak_ptr<T> by design safely refers to an object which may or may not still exist. It does not offer operator-> or operator* since you have to make sure the object still exists before you can try to access it.

To access an object referred to by a std::weak_ptr you first call lock() which returns a std::shared_ptr . Then, you need to check if that std::shared_ptr refers to an 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). If it doesn't then the std::weak_ptr was referring to a destroyed object which you can't access anymore.

Example :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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