Recently, I encountered a situation in the program, but I used another method to bypass it. The specific problems are as follows:
Const Layer & Frame: GetLayer (uint32 layerIndex) const
{
If (CheckLayerIndexValid (layerIndex ))
{
Return m_layers [layerIndex];
}
Return ?; // What? How?
}
In this case, we can change to the return pointer:
Const Layer * Frame: GetLayer (uint32 layerIndex) const
{
If (CheckLayerIndexValid (layerIndex ))
{
Return m_layers [layerIndex];
}
Return 0;
}
Or return as a parameter:
Bool Frame: GetLayer (uint32 layerIndex, Layer & layer) const
{
If (CheckLayerIndexValid (layerIndex ))
{
Layer = m_layers [layerIndex];
Return true;
}
Return false;
}
But what if we want to maintain the first function form, but want to return the object reference?
I think of the Null Object Mode. When a meaningless object is required, I can return a pre-determined empty object, similar to the code below:
# Include <boost/shared_ptr.hpp>
Template <class T>
Class Nullable
{
Protected:
Nullable (){}
Virtual ~ Nullable (){}
Public:
Static boost: shared_ptr <T> & NullPtr ()
{
Return ms_nullPtr;
}
Bool IsNull ()
{
Return this = ms_null;
}
Private:
Static T * Null ()
{
If (0 = ms_null)
{
Ms_null = new T;
}
Return ms_null;
}
Private:
Static T * ms_null;
Static boost: shared_ptr <T> ms_nullPtr;
};
Template <class T>
T * Nullable <T>: ms_null = 0;
Template <class T>
Boost: shared_ptr <T> Nullable <T>: ms_nullPtr (Nullable: Null ());
Class Layer: public Nullable <Layer>
{
Public:
Layer (){}
~ Layer (){}
Public:
Int m_id;
};
In the above case, we can return * Layer: NullPtr (), but in this case, we must check whether IsNull () is valid after obtaining the function return value, A little troublesome. In addition, when an empty object instead of a reference is returned,
IsNull () is no longer valid.
My example is not very suitable. Now the layerIndex in this example should be valid, but if a Manager stores a series of layer with id as the key value, you need to find the corresponding layer Based on the id. It is normal that the layer cannot be found at this time. It should not be an error or exception at this time.