Search code examples
c++shared-ptrsmart-pointerscopy-on-write

Copy-on-write pointer object in C++


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?


Solution

  • 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);