Search code examples
c++weak-ptr

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


In a lambda function, instead of this, I was trying to use weak_ptr to access all member function and variable, but I'm getting this error:

operator -> or ->* applied to "const std::weak_ptr" instead of to a pointer type


Solution

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