47 lines
759 B
C++
47 lines
759 B
C++
// Implementation from https://www.youtube.com/watch?v=9b9hWIH8-hE
|
|
|
|
#include <memory>
|
|
|
|
namespace Core {
|
|
template<class T>
|
|
class CowPtr
|
|
{
|
|
public:
|
|
explicit CowPtr(T* t) : content(t)
|
|
{
|
|
}
|
|
|
|
T& operator*()
|
|
{
|
|
detach();
|
|
return *content;
|
|
}
|
|
const T& operator*() const
|
|
{
|
|
return *content;
|
|
}
|
|
|
|
T* operator->()
|
|
{
|
|
detach();
|
|
return content.operator->();
|
|
}
|
|
|
|
const T* operator->() const
|
|
{
|
|
return content.operator->();
|
|
}
|
|
|
|
std::shared_ptr<T> content;
|
|
|
|
private:
|
|
void detach()
|
|
{
|
|
T* tmp = content.get();
|
|
if(!(tmp == 0 || content.unique()))
|
|
{
|
|
content = std::shared_ptr<T>(new T(*tmp));
|
|
}
|
|
}
|
|
};
|
|
} // namespace Core
|