liveBook · Manning

Std::shared_ptr

As explained in C++ Concurrency in Action, Second Edition

`std::shared_ptr` is a C++ standard library smart pointer that shares ownership of a dynamically allocated object.

A lock-free stack can store each value in a std::shared_ptr allocated when the value is pushed. Its pop() returns the pointer, or an empty pointer when the stack is empty; allocating during push avoids a potentially throwing allocation during pop(). section 7.2.1

Listing 7.3. A lock-free stack that leaks nodes
template<typename T>
class lock_free_stack
{
private:
    struct node
    {
        std::shared_ptr<T> data;                                      #1
        node* next;
        node(T const& data_):
            data(std::make_shared<T>(data_))                          #2
        {}
    };
    std::atomic<node*> head;
public:
    void push(T const& data)
    {
        node* const new_node=new node(data);
        new_node->next=head.load();
        while(!head.compare_exchange_weak(new_node->next,new_node));
    }
    std::shared_ptr<T> pop()
    {
        node* old_head=head.load();
        while(old_head &&                                             #3
            !head.compare_exchange_weak(old_head,old_head->next));
        return old_head ? old_head->data : std::shared_ptr<T>();      #4
    }
};

The listing uses std::shared_ptr<T> for node data and returns the removed node’s pointer, while leaving node reclamation unresolved. section 7.2.1

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Demonstrates shared_ptr in a lock-free stack, but leaves node reclamation unresolved.
Examples
Uses a lock-free stack whose push allocates shared data and whose pop returns a pointer or an empty value.
What you can do after
Apply std::shared_ptr to return stack data without a throwing allocation during pop().
How it connects
Connects shared_ptr with lock-free stacks, heap allocation, and exception safety.

Also explained in

Compare how 2 books explain std::shared_ptr →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.