From 6b250ad8e7808384e0c03644a5bf8c43ae3c5245 Mon Sep 17 00:00:00 2001 From: Determinant Date: Wed, 11 Jul 2018 18:58:54 -0400 Subject: use copy-and-swap idiom --- promise.hpp | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/promise.hpp b/promise.hpp index fe701ae..593d5c1 100644 --- a/promise.hpp +++ b/promise.hpp @@ -126,21 +126,35 @@ namespace promise { class promise_t { Promise *pm; size_t *ref_cnt; - inline void clear(); public: friend Promise; template friend promise_t all(const PList &promise_list); template friend promise_t race(const PList &promise_list); inline promise_t(); + inline ~promise_t(); template inline promise_t(Func callback); - ~promise_t() { clear(); } + + void swap(promise_t &other) { + std::swap(pm, other.pm); + std::swap(ref_cnt, other.ref_cnt); + } promise_t &operator=(const promise_t &other) { - clear(); - pm = other.pm; - ref_cnt = other.ref_cnt; - ++*ref_cnt; + if (this != &other) + { + promise_t tmp(other); + tmp.swap(*this); + } + return *this; + } + + promise_t &operator=(promise_t &&other) { + if (this != &other) + { + promise_t tmp(std::move(other)); + tmp.swap(*this); + } return *this; } @@ -623,7 +637,7 @@ namespace promise { pm(new Promise()), ref_cnt(new size_t(1)) {} - inline void promise_t::clear() { + inline promise_t::~promise_t() { if (pm) { if (--*ref_cnt) return; -- cgit v1.2.3