Last active
December 23, 2015 19:59
-
-
Save SeanCline/6686637 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <memory> | |
#include <utility> | |
#include <cassert> | |
template <typename T> | |
class cow_ptr | |
{ | |
public: | |
typedef T value_type; | |
cow_ptr(value_type* x = nullptr) | |
: sp_(x) | |
{ } | |
cow_ptr(const cow_ptr& x) | |
: sp_(x.sp_) | |
{ } | |
template<class X, class Deleter> | |
cow_ptr(std::unique_ptr<X, Deleter> up) | |
: sp_(std::move(up)) | |
{ } | |
~cow_ptr() | |
{ } | |
cow_ptr& operator=(std::nullptr_t) | |
{ sp_.reset(); return *this; } | |
cow_ptr& operator=(cow_ptr x) | |
{ sp_ = x.sp_; return *this; } | |
template<class X, class Deleter> | |
cow_ptr& operator=(std::unique_ptr<X, Deleter> up) | |
{ sp_ = std::move(up); return *this; } | |
const value_type& read() const | |
{ return *sp_; } | |
const value_type& operator*() const | |
{ return read(); } | |
const value_type* operator->() const | |
{ return &read(); } | |
value_type& write() | |
{ | |
if (!sp_.unique()) { | |
sp_ = std::make_shared<value_type>(*sp_); //< Copy the owned object under our _sole_ ownership. | |
} | |
assert(sp_.unique() && "Assignment above failed to produce a unique shared_ptr."); | |
return *sp_; //< We are the sole owner, we can return a ref to non-const. | |
} | |
private: | |
std::shared_ptr<value_type> sp_; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment