juce::WeakReference atomicity

Say I have a juce::WeakReference<MyObject> as suggested in the documentation - what happens if I try to access a pointer returned by the WeakReference, if the original pointer is deleted by another thread in a multi-threaded situation?

    MyObject* n = new MyObject();
    WeakReference<MyObject> myObjectRef = n;

    MyObject* pointer1 = myObjectRef;  // returns a valid pointer to 'n'

    // some other thread deletes n at this point

    pointer1->doSomething(); // behaviour?

Is it even possible to safely use WeakReference in a multi-threaded environment without locking, if there are no guarantees that the underlying pointer is still valid right after checking if it is?

No, WeakReference was never designed to be thread-safe.

I figured. I was just a little confused, as the documentation indicates it may be used in a multi-threaded environment:

            // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose
            // to create a WeakReference to the object here in the constructor, [...]

Sure - the message is a bit confusing, but the point is that you could use it as long as you lock around all the uses of WeakReference. It might be better if I change that comment to just warn that the whole thing is unsafe!

Thank you very much for the clarification :slight_smile: