Copy to write using shared_ptr

So, I have a simple one cow_ptr. It looks something like this:

template<class T, class Base=std::shared_ptr<T const>>
struct cow_ptr:private Base{
  using Base::operator*;
  using Base::operator->;
  using Base::operator bool;
  // etc

  cow_ptr(std::shared_ptr<T> ptr):Base(ptr){}

  // defaulted special member functions

  template<class F>
  decltype(auto) write(F&& f){
    if (!unique()) self_clone();
    Assert(unique());
    return std::forward<F>(f)(const_cast<T&>(**this));
  }
private:
  void self_clone(){
    if (!*this) return;
    *this = std::make_shared<T>(**this);
    Assert(unique());
  }
};

this ensures that it contains non-const Tand guarantees that it uniqueis when it is .write([&](T&){})given to it.

depreciation .unique()seems to indicate that this project is erroneous.

I assume that if we start with cow_ptr<int> ptrc 1in stream A, pass it to stream B, make it unique, change it to 2, go ptrback and read it in thread, Awe created a race condition.

How to fix it? Can I just add a memory barrier to write? Which one of? Or is the problem more fundamental?

x86 - x86 , ++?

+6
1

, , , :

if(sp.unique()) { 
    // some deinitialisation
} else {
    // somebody else will deinitialise.
}

, , 2 .

,

  • - ,
  • , ( )

, , shared_ptr .

use_count == 1

0

All Articles