C++ Logo

std-proposals

Advanced search

Re: [std-proposals] A non-owning but self zeroing smart pointer for single ownership

From: JOHN MORRISON <inglesflamenco_at_[hidden]>
Date: Thu, 20 Feb 2025 21:49:32 +0000
Ok, there is a real thread safety issue, it is serious and I have been working on it.

Here is the horror scenario;

The rule that singly owned objects shouldn't be visible to other threads isn't necessarily one that we are conscious of but we follow it because we wouldn't trust a raw pointer for the job and there is no smart pointer available. That is probably what has kept us in line and out of trouble. But if a smart pointer becomes available in the form of ptr_to_unique then it could be tempting to believe that one of its roles is to do that job safely. The code you write will look neat and tidy and you will find that it compiles and appears to work correctly. The chance that another thread does a delete between testing and use is almost vanishingly small. It may not bite until your software has been delivered and is in service by which time your code has, to quote from comments here “a large surface area of subtle bugs”.

The solution is to detect when ptr_to_unique is being used outside of its intended scope (i.e. referencing something in another thread) and throw an exception because no good will come of it. This can be done but the price is the extra overhead of storing a thread ID on the control block and a call to std::this_thread::get_id() before every test or dereference. My stress tests have found this to have no perceptible impact on performance.

This leaves ptr_to_unique fully functional in its intended domain of single ownership not visible to other threads. This is a very large domain in which most code still resides and it is where its use cases will be found e.g. the GUI thread of an application where a retained pointer can easily outlive its pointee. But if you step outside of that and do something that you shouldn't, then it will throw an exception. That seems reasonable to me.

I have updated the implementation and Readme in the GitHub repository https://github.com/make-cpp-nice/ptr_to_unique

I am now keen to know how any of you see this fix. Does it adequately address the concerns about thread safety? And if so, what other concerns or objections remain.



Received on 2025-02-20 21:49:35