Search code examples
shared-ptr

Is this code dereferencing a pointer or doing something else?


I've never seen this kind of thing before - I'm a little new to shared_ptr - is this a typical operation with a shared pointer, or is someone doing something a little fancy here? It doesn't seem like a dereference - it looks more like someone's trying to make sure the operator->() is defined...

I've done a google/duckduckgo on this in as many ways as I can think of, can't find any good examples online.

Thanks.

void fn(std::shared_ptr<int> data){
if(data.operator->() == NULL){
return; //this is an error
}

....//rest of function, doesn't matter

}

Solution

  • By

    T* operator->() const noexcept;
    

    you are accessing internal pointer of shared_ptr. If it is not NULL you can read data pointed by this pointer. To do it you must use:

    T& operator*() const noexcept;
    

    So when you want to check if shared_ptr points some data and read it, you could write:

    void fn(std::shared_ptr<int> data) {
        if(data.operator->() == NULL) // dereference pointer
           return; //this is an error
    
        int value = data.operator*(); // dereference data pointed by pointer
    }
    

    The code above is rather fancy way of using shared_ptr instances. Instead of calling operators like member functions - obj.operator @() you can use shorter form by applying @obj:

     // this code does the same thing as above
    void fn2(std::shared_ptr<int> data)
    {
        if(!data)
           return; //this is an error
    
        int value = *data;
        std::cout << value << std::endl;
    }
    

    For more details, see reference.