diff --git a/include/libtorrent/copy_ptr.hpp b/include/libtorrent/copy_ptr.hpp index 953dfc0e1..e02c33577 100644 --- a/include/libtorrent/copy_ptr.hpp +++ b/include/libtorrent/copy_ptr.hpp @@ -33,46 +33,34 @@ POSSIBILITY OF SUCH DAMAGE. #ifndef TORRENT_COPY_PTR #define TORRENT_COPY_PTR +#include + namespace libtorrent { template struct copy_ptr { - copy_ptr(): m_ptr(nullptr) {} + copy_ptr() = default; explicit copy_ptr(T* t): m_ptr(t) {} copy_ptr(copy_ptr const& p): m_ptr(p.m_ptr ? new T(*p.m_ptr) : nullptr) {} - copy_ptr(copy_ptr&& p) noexcept : m_ptr(p.m_ptr) { p.m_ptr = nullptr; } + copy_ptr(copy_ptr&& p) noexcept = default; - void reset(T* t = nullptr) { delete m_ptr; m_ptr = t; } + void reset(T* t = nullptr) { m_ptr.reset(t); } copy_ptr& operator=(copy_ptr const& p) { if (m_ptr == p.m_ptr) return *this; - T* c = p.m_ptr ? new T(*p.m_ptr) : nullptr; - delete m_ptr; - m_ptr = c; + m_ptr.reset(p.m_ptr ? new T(*p.m_ptr) : nullptr); return *this; } - copy_ptr& operator=(copy_ptr&& p) noexcept { - if(m_ptr == p.m_ptr) return *this; - delete m_ptr; - m_ptr = p.m_ptr; - p.m_ptr = nullptr; - return *this; - } - T* operator->() { return m_ptr; } - T const* operator->() const { return m_ptr; } + copy_ptr& operator=(copy_ptr&& p) noexcept = default; + T* operator->() { return m_ptr.get(); } + T const* operator->() const { return m_ptr.get(); } T& operator*() { return *m_ptr; } T const& operator*() const { return *m_ptr; } - void swap(copy_ptr& p) - { - T* tmp = m_ptr; - m_ptr = p.m_ptr; - p.m_ptr = tmp; - } - explicit operator bool() const { return m_ptr != nullptr; } - ~copy_ptr() { delete m_ptr; } + void swap(copy_ptr& p) { std::swap(*this, p); } + explicit operator bool() const { return m_ptr.get() != nullptr; } private: - T* m_ptr = nullptr; + std::unique_ptr m_ptr; }; } diff --git a/test/test_torrent_info.cpp b/test/test_torrent_info.cpp index a239d8756..a5b31dc65 100644 --- a/test/test_torrent_info.cpp +++ b/test/test_torrent_info.cpp @@ -1008,3 +1008,19 @@ TORRENT_TEST(copy) TEST_EQUAL(fs2.hash(i), file_hashes[i]); } } + +struct A +{ + int val; +}; + +TORRENT_TEST(copy_ptr) +{ + copy_ptr a(new A{4}); + copy_ptr b(a); + + TEST_EQUAL(a->val, b->val); + TEST_CHECK(&*a != &*b); + a->val = 5; + TEST_EQUAL(b->val, 4); +}