C++ Logo

std-discussion

Advanced search

Re: Lack of ordering guarantees in shared_ptr wording

From: Nate Eldredge <nate_at_[hidden]>
Date: Sat, 15 Feb 2025 16:38:33 -0700
On Feb 15, 2025, at 15:30, Jennifier Burnett via Std-Discussion <std-discussion_at_[hidden]> wrote:

> Basically, I think there's issues with the standard's wording around shared_ptr, and I'd prefer to make sure I've actually found something before starting a defect report against a decade old library class.

I'm guessing you're the same person who recently asked this on Stack Overflow (https://stackoverflow.com/questions/79424997/exactly-how-thread-unsafe-is-shared-ptr-supposed-to-be?noredirect=1#comment140073062_79424997). I agree with you that there is an issue.

I came up with an example that is, to my mind, a little simpler and more explicit (https://godbolt.org/z/PMMKK9d7r):

#include <memory>
#include <thread>
#include <iostream>

class Wobble {
public:
    Wobble() : x(0) { }
    void frob() { x = 42; }
    ~Wobble() {
        std::cout << x << std::endl;
    }
private:
    int x;
};

std::shared_ptr<Wobble> p, q;

void thr1() {
    p->frob();
    p.reset();
}

void thr2() {
    q.reset();
}

int main() {
    p = q = std::make_shared<Wobble>();
    std::jthread t1(thr1), t2(thr2);
    return 0;
}

I think we all hope that this program does not contain a data race, and is guaranteed to print 42.

To prove that, we need to ensure that frob() happens-before ~Wobble(), to avoid a data race on the x member. And I don't see that shared_ptr offers any guarantees that allow us to reach that conclusion.

Received on 2025-02-15 23:38:50