* Default constructor. Creates an OwnerPointer that does not own any object.
*/
OwnerPointer()
+ : mObject(NULL)
{
- mObject = NULL;
}
/**
* @param[in] object A pointer to a heap allocated object.
*/
OwnerPointer( T* object )
+ : mObject(object)
{
- mObject = object;
}
/**
* Copy constructor. Passes the ownership of a pointer to another.
* @param[in] other The pointer that gives away the ownership.
*/
- OwnerPointer( OwnerPointer& other )
+ OwnerPointer( const OwnerPointer& other )
+ : mObject(NULL)
{
- Init( other );
+ // other needs to be const for compiler to pick up this as copy constructor;
+ // though we are using this as move as there can only be one owner
+ Swap( const_cast<OwnerPointer&>( other ) );
}
/**
{
if( this != &other ) // no self-assignment
{
- Reset();
- Init( other );
+ // Creation of temportaty object to prevent premature deletion of object
+ OwnerPointer(other).Swap(*this);
}
// return self
* Returns a const pointer to the object owned.
* @return a const pointer to the object.
*/
- const T* Get()
+ const T* Get() const
{
return mObject;
}
+ /**
+ * Swap owned objects
+ */
+ void Swap( OwnerPointer& other )
+ {
+ T* tmp = mObject;
+ mObject = other.mObject;
+ other.mObject = tmp;
+ }
+
// Handle comparisons - This is a variation of the safe bool idiom
/**
*/
void ThisIsSaferThanReturningVoidStar() const {}
-private:
-
- /**
- * Initialise this pointer from another one.
- * ownerPointer parameter looses ownership.
- * @param ownerPointer owner pointer
- */
- void Init( OwnerPointer& ownerPointer )
- {
- mObject = ownerPointer.mObject;
- ownerPointer.mObject = NULL;
- }
-
// data
T* mObject; ///< Raw pointer to the object
};