简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM