2

I tried to follow this article http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Copy-on-write on how to implement copy on write pointers in C++. The problem is, it doesn't work for me.

The crux of the object is in overloading the dereference operator (*) to do background copying if it should return a non-const reference:

   const T& operator*() const
    {
        return *m_sp;
    }
    T& operator*()
    {
        detach();
        return *m_sp;
    }

Sadly, it seems that only the second version is ever run. C-outing the my pointed-to object creates a copy, even doing something like

   CowPtr<string> my_cow_ptr(new string("hello world"));
   const string& const_ref=*my_cow_ptr; 

causes the detach() function to run.

Any ideas on why it's not working as advertised?

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142

1 Answers1

1

The const member function will be called on a const object. so:

const CowPtr<std::string> my_const_cow_ptr(new std::string("Hello, world"));
const std::string& str = *my_const_cow_ptr;

or

CowPtr<std::string> my_cow_ptr(new std::string("Hello, world"));
const std::string& str = *static_cast<const CowPtr<std::string>&>(my_cow_ptr);
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • But that also means that aside of const-casting, on every call, there is no way the compiler will know to call each function automatically... so the whole point of copy-on-write goes down the drain. – Born2Smile Oct 08 '16 at 13:41