Two-Phase Construction and Object Destruction: Fundamentals of Symbian C++
Two-Phase Construction and Object Destruction: Fundamentals of Symbian C++
Two-Phase Construction and Object Destruction: Fundamentals of Symbian C++
This work is licensed under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
To view a copy of this license, visit http://creativecommons.org/licenses/bysa/2.0/uk/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California,
94105, USA.
Two Phase Construction
and Object Destruction
Introduction
Two-Phase Construction
• Know why code should not leave inside a constructor
• Recognize that two-phase construction is used to avoid the
accidental creation of objects with undefined state
• Understand that constructors and second-phase ConstructL()
methods are given private or protected access specifiers in classes
which use two-phase construction, to prevent their inadvertent use
• Understand how to implement two-phase construction, and how to
construct an object which derives from a base class which also
uses a two-phase method of initialization
• Know the Symbian OS types (C classes) which typically use two-
phase construction
Two-Phase Construction
Two-Phase Construction
void ConstructL()
{
iBar = new (ELeave) CBar(iVal);
}
private:
CBar* iBar;
};
...
CFoo* foo = new (ELeave)CFoo(42);
CleanupStack::PushL(foo);
foo->ConstructL();
CleanupStack::Pop(foo);
The idiom
• Is best implemented if the class itself makes the call to the second-phase
construction function, rather than the caller
• Obviously the code cannot do this from within the simple constructor, since this
takes it back to the original problem of calling a method which may leave
A class intended
• For extension through inheritance which uses the two-phase
construction pattern typically supplies a protected method to do this
• Called BaseConstructL() rather than ConstructL()
Object Destruction
• Know that it is neither efficient nor necessary to set a pointer to
NULL after deleting it in destructor code
• Understand that a destructor must check before dereferencing a
pointer in case it is NULL, but need not check if simply calling
delete on that pointer
Object Destruction
When implementing
• The standard Symbian OS two-phase construction idiom it is
important to consider the destructor code carefully
• A destructor must be coded to release all the resources that an
object owns
• The destructor may be called to clean up partially constructed
objects if a leave occurs in the second-phase ConstructL()
function
But ...
Object Destruction
CExample::~CExample()
{
if (iMyAllocatedMember) // iMyAllocatedMember may be NULL
{
iMyAllocatedMember->DoSomeCleanupPreDestruction();
delete iMyAllocatedMember; // No need to set it to NULL
}
}
Two-Phase Construction
Object Destruction