Fix ref::operator= for non-const lvalue binding to a temporary.
authorRobert Sesek <rsesek@bluestatic.org>
Sat, 8 Oct 2016 19:29:59 +0000 (15:29 -0400)
committerRobert Sesek <rsesek@bluestatic.org>
Sat, 8 Oct 2016 19:34:45 +0000 (15:34 -0400)
Implement operator= manually and reimplement the copy-ctor using it, rather than
vice versa. In addition, deleter_ gets changed to a pointer rather than
reference, so that a default ctor can be added.

test.cc
zcpointer.h

diff --git a/test.cc b/test.cc
index 92da993..4ea07e0 100644 (file)
--- a/test.cc
+++ b/test.cc
@@ -38,7 +38,10 @@ void TestReset() {
 template <typename T>
 void TestUnwrap() {
   zc::owned<T> t(new T());
-  T* unwrap = t.get();
+  //T* unwrap = t.get();
+
+  zc::ref<T> ref = t.get();
+  T* unwrap2 = ref;
 }
 
 void TestMove() {
@@ -52,6 +55,17 @@ void TestMove() {
   owned->DoThing();
 }
 
+void PtrHelper(zc::ref<C>* out) {
+  zc::owned<C> c(new C());
+  *out = c.get();
+}
+
+void TestPtr() {
+  zc::ref<C> ref;
+  PtrHelper(&ref);
+  ref->DoThing();
+}
+
 int main() {
-  TestMove();
+  TestPtr();
 }
index ce4a821..bf86fb5 100644 (file)
@@ -86,23 +86,29 @@ class owned : public std::unique_ptr<T, internal::OwnedPtrDeleter<T>> {
 template <typename T>
 class ref {
  public:
-  explicit ref(owned<T>& o) : ptr_(o.GetRawPointer()), deleter_(o.get_deleter()) {
-    deleter_.AddRef(this);
+  ref() : ptr_(nullptr), deleter_(nullptr), deleted_(true) {}
+
+  explicit ref(owned<T>& o) : ptr_(o.GetRawPointer()), deleter_(&o.get_deleter()) {
+    deleter_->AddRef(this);
   }
 
-  ref(const ref<T>& o) : ptr_(o.ptr_), deleter_(o.deleter_), deleted_(o.deleted_) {
-    if (!deleted_) {
-      deleter_.AddRef(this);
-    }
+  ref(const ref<T>& o) {
+    *this = o;
   }
 
-  ref<T>& operator=(ref<T> o) {
-    return ref(o);
+  ref<T>& operator=(const ref<T>& o) {
+    ptr_ = o.ptr_;
+    deleter_ = o.deleter_;
+    deleted_ = o.deleted_;
+    if (!deleted_) {
+      deleter_->AddRef(this);
+    }
+    return *this;
   }
 
   ~ref() {
     MarkDeleted();
-    deleter_.RemoveRef(this);
+    deleter_->RemoveRef(this);
   }
 
   T* operator->() const {
@@ -125,7 +131,7 @@ class ref {
   }
 
   T* ptr_;
-  internal::OwnedPtrDeleter<T>& deleter_;
+  internal::OwnedPtrDeleter<T>* deleter_;
   bool deleted_ = false;
 };