Last active
July 27, 2018 17:37
-
-
Save W4RH4WK/8212fc6606148841352619e27e03610f to your computer and use it in GitHub Desktop.
Copy On Write Shared Ptr
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
#include <iostream> | |
#include <memory> | |
struct vec3 { | |
int x, y, z; | |
}; | |
std::ostream& operator<<(std::ostream& out, const vec3& v) | |
{ | |
return out << "vec3{" << v.x << ", " << v.y << ", " << v.z << "}"; | |
} | |
template <typename t> | |
class cow_ptr : public std::shared_ptr<t> { | |
public: | |
t& operator*() noexcept | |
{ | |
this->reset(new t(*this->get())); | |
return *this->get(); | |
} | |
const t& operator*() const noexcept | |
{ | |
return *this->get(); | |
} | |
t* operator->() noexcept | |
{ | |
this->reset(new t(*this->get())); | |
return this->get(); | |
} | |
const t* operator->() const noexcept | |
{ | |
return this->get(); | |
} | |
}; | |
template <typename t> | |
std::ostream& operator<<(std::ostream& out, const cow_ptr<t>& cow) | |
{ | |
return out << cow.get() | |
<< " (" << cow.use_count() << ") " | |
<< *cow; | |
} | |
int main() | |
{ | |
cow_ptr<vec3> cow1, cow2; | |
cow1.reset(new vec3{ 1, 2, 3 }); | |
cow2 = cow1; | |
std::cout << "cow1: " << cow1 << "\n"; | |
std::cout << "cow2: " << cow2 << "\n\n"; | |
cow1->y = 5; | |
std::cout << "cow1: " << cow1 << "\n"; | |
std::cout << "cow2: " << cow2 << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment