Commits

Lenard Lindstrom  committed ccebe7a

Add the * operator to dereference Reference and ClassReference references.

The * operator makes it easier to use overloaded operators on the referenced
object.

  • Participants
  • Parent commits de100e6

Comments (0)

Files changed (2)

File include/imgblit/memory.hpp

             ref_datum_p(add_ref(other.ref_datum_p)) { }
         virtual ~Reference() { dec_ref(ref_datum_p); };
         Datum *operator ->() const { assert(ref_datum_p); return ref_datum_p; }
+        Datum &operator *() const { assert(ref_datum_p); return *ref_datum_p; }
         Reference &operator =(const Reference &rvalue);
         bool operator !() const { return ref_datum_p == 0; }
     protected:
         ClassReference<D> &operator =(const Reference &rvalue);
         operator Reference() { return Reference(ref_datum_p); }
         D *operator ->() const { assert(ref_datum_p); return ref_datum_p; }
+        D &operator *() const { assert(ref_datum_p); return *ref_datum_p; }
         bool operator !() const { return ref_datum_p == 0; }
     protected:
         static void inc_ref(Datum *r) { Reference::inc_ref(r); }

File test/testmemory.cpp

 #include <cassert>
 #include <sstream>
 #include <ostream>
+#include <string>
+#include <cstring>
 
 using namespace imgblit;
 using std::stringstream;
 using std::ostream;
+using std::string;
+using std::strcmp;
 
 
 void test_delete();
 void test_ref_count();
 void test_null_check();
 void test_ostream();
+void test_dereferencing();
 
 int main()
 {
     test_null_check();
     test_delete();
     test_ostream();
+    test_dereferencing();
 
     return 0;
 }
     capture << ClassReference<WriteSomething>(new WriteSomething);
     assert(capture.str() == "<Something>");
 }
+
+
+// A reference object can be accessed using either the `*` or `->` operators.
+class MyString : public string, public Datum {
+
+public:
+    MyString() : string("") { }
+    MyString(const char *value) : string(value) { }
+    void write(ostream &os) const;
+};
+
+void
+MyString::write(ostream &os) const
+{
+    os << '(' << this->c_str() << ')';
+}
+
+typedef ClassReference<MyString> MyStringRef;
+
+void
+test_dereferencing()
+{
+    stringstream capture;
+    MyStringRef a(new MyString("1234"));
+    assert((*a)[1] == '2');
+    assert(strcmp(a->c_str(), "1234") == 0);
+    (*a)[0] = 'X';
+    assert(strcmp(a->c_str(), "X234") == 0);
+
+    Reference b(a);
+    b->write(capture);
+    assert(capture.str() == "(X234)");
+    capture.str("");
+    (*b).write(capture);
+    assert(capture.str() == "(X234)");
+}