|
Boost : |
Subject: Re: [boost] Why no non-null smart pointers?
From: Jeff Hill (johill_at_[hidden])
Date: 2014-04-29 10:32:54
> You've overlooked the use case of reclaiming ownership from smart_ptr.
Sorry, apparently a bit more explanation is needed.
In the code above I have this assignment.
*this = NullObjectTypes < T > :: factory ();
My idea is that shared_ptr <T> is returned from this factory function so
that it can be assigned to *this, and so ownership /is/ properly maintained.
The default templated version of NullObjectTypes < T > :: factory () would
return a default constructed shared_ptr <T>. This is necessary of course for
backwards compatibility.
template < class T >
struct NullObjectTypes
shared_ptr < ChessPiece > factory () { return shared_ptr < T > (); }
};
The benefit comes when T is an interface class. In this situation we can
specialize NullObjectTypes < T > as follows.
Lets say that T is the ChessPiece class, and we will implement the null
object pattern for it.
struct ChessPiece {
virtual void move() = 0;
};
struct ChessPieceNull : public ChessPiece {
void move() {}
};
template <>
NullObjectTypes < ChessPiece >
shared_ptr < ChessPiece > factory ();
};
template <>
shared_ptr < ChessPiece > NullObjectTypes < ChessPiece > :: factory ()
{
static ChessPieceNull chessPieceNull;
return shared_ptr < ChessPiece > ( &chessPieceNull, nullDeleter () );
}
-- View this message in context: http://boost.2283326.n4.nabble.com/Why-no-non-null-smart-pointers-tp2642959p4661817.html Sent from the Boost - Dev mailing list archive at Nabble.com.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk