18 unique_interface_ptr

A unique_interface_ptr is a smart pointer which represents exclusive ownership of an object that implements interface IObject and will call the Destroy method when it destructs.

Consider the following $interface definitions and a class that implements them:


$interface+ Ix : ceda::IObject
{
    int get() const;
};

$interface+ Iy : Ix
{
    void set(int x);
};

$class X isa Iy
{
public:
    X(int x) : x(x) {}
    int get() const { return x; }
    void set(int v) { x = v; }
private:
    int x;
};

X implements interface IObject so therefore a Destroy method is generated by the compiler which calls delete this.


void X::Destroy() const
{
    delete this;
}

In the following example the variable p which is a unique_interface_ptr takes ownership of the dynamically allocated instance of class X ensuring it is deleted:


void main()
{
    ceda::unique_interface_ptr<Iy> p(new X(10));
    assert( p->get() == 10 );
}

If D is a sub-interface of B, then unique_interface_ptr<D> is implicitly convertible to unique_interface_ptr<B>.

In many ways a unique_interface_ptr is analogous to a std:::unique_ptr :

  • The smart pointer owns and manages another object through a pointer and disposes of that object when the smart pointer goes out of scope
  • The smart pointer may alternatively own no object, in which case it is called empty
  • The default constructor or the constructor which is given a nullptr initialises the smart pointer to empty
  • The unique_interface_ptr class explicitly deletes its lvalue copy constructor and lvalue assignment operator.
  • The smart pointer can be assigned a new value using operator= or reset and that causes the previous object managed by the smart pointer to be disposed. Furthermore, a call to reset() or reset(nullptr) or operator= with nullptr clears the smart pointer (i.e. makes it empty)
  • There is an (explicit) conversion to bool which is true if and only if the smart pointer is non-empty
  • The method release releases ownership of the managed object. A pointer to the object is returned and the caller must take on responsibility for disposing of the object. The smart pointer becomes empty after calling release.
  • The method get returns a pointer to the managed object.
  • operator* and operator-> allow the smart pointer to be used like a raw pointer.
  • The comparison operators operator==, operator!=, operator<<, operator<=, operator>, operator>= allow for comparing to another unique_interface_ptr or with nullptr.