N4058: Atomic Smart Pointers -- Herb Sutter

A new WG21 paper is available. A copy is linked below, and the paper will also appear in the next normal WG21 mailing. If you are not a committee member, please use the comments section below or the std-proposals forum for public discussion.

Document number: N4058

Date: 2014-06-12

Atomic Smart Pointers

by Herb Sutter

Excerpt:

We encourage that modern C++ code should avoid all uses of owning raw pointers and explicit delete. Instead, programmers should use unique_ptr and shared_ptr (with weak_ptr), as this is known to lead to simpler and leak-free memory-safe code. This is especially important when lifetimes are unstructured or nondeterministic, which arises especially in concurrent code, and it has long been well-known that the smart pointers would be useful there; for an example, see [1].

Unfortunately, lock-free code is still mostly forced to use owning raw pointers. Our unique_ptr, shared_ptr, and weak_ptr would directly benefit lock-free code just as they do regular code (see next section), but they are not usable easily or at all in lock-free code because we do not support atomic<unique_ptr<T>>, atomic<shared_ptr<T>>, and atomic<weak_ptr<T>>.

...

If we had atomic<unique_ptr<T>> we could (and should) write the following equivalent code that is safer, no slower, and less error-prone because we can directly express the unique ownership semantics including ownership transfer:

atomic<unique_ptr<X>> p_root;
void producer() {
    auto temp = make_unique<X>();
    load_from_disk_and_store_in( *temp ); // build data structure
    p_root = move(temp);                  // atomically publish it
}
This righteous code should be supported...

Add a Comment

Comments are closed.

Comments (1)

0 0

Jeremy Wong said on Jul 29, 2014 09:59 AM:

In my attack to the problem of atomic_shared_ptr<T> and atomic_weak_ptr<T>, the solution was surprisingly elegant when some assumptions were made. This solution supports T having copy constructor. Therefore, please consider to name atomic_copy<shared_ptr<T>> instead of atomic<shared_ptr<T>>. Why bother specialization then?