Single Phase Constructor Tutorial

Single phase construction is enabled by defining the CONSTRUCTORS_MAY_LEAVE() macro in a public section of a class definition if the single phase construction is part of the public interface of the class.

Context

Single phase constructor provides a means to use the RAII concepts for Symbian Developers who are familiar with C++ standards. It is provided as a tool and needs to be used after careful consideration.

Prerequisites

Required background

Before beginning you must know the following:

  • RAII: The Resource Acquisition Is Initialization (RAII) idiom is the basis of the implementation of the smart pointer class templates.

  • CONSTRUCTORS_MAY_LEAVE(): This macro is used for enabling single phase construction, particularly for CBase-derived classes.

Steps

  1. Enabling single phase constructor

    Example: Single phase construction is enabled by defining the CONSTRUCTORS_MAY_LEAVE() macro in a public section of a class definition if the single phase construction is part of the public interface of the class. An example of this is given below:

    class CManagedUserSinglePhase : public CBase
    	{
    public:
    	CONSTRUCTORS_MAY_LEAVE
    	static CManagedUserSinglePhase* NewL(CTicker* aTicker)
    		{
    		return new(ELeave) CManagedUserSinglePhase(aTicker);
    		}
    	. . .
    	}	
  2. Using single phase constructor

    Example: This macro must be used within a public section of a class definition, if the single phase construction is part of the public interface of the class. Other classes, not derived from CBase will not be affected by this macro.

    The following example code snippet the class demonstrates the use of an embedded string in the ingle-phase construction pattern, where a leave-safe constructor fully initializes the object.

    class CStringUserSinglePhase : public CBase
    	{
    public:
    		CONSTRUCTORS_MAY_LEAVE
    
    	static CStringUserSinglePhase* NewL(const TDesC& aName)
    		{
    		return new(ELeave) CStringUserSinglePhase(aName);
    		}
    
    	~CStringUserSinglePhase()
    		{
    		
    		}
  3. Need to declare the CONSTRUCTORS_MAY_LEAVE macro

    Example: This is necessary because the Symbian platform currently lacks the placement delete operator counterparts corresponding to the CBase placement new operators that take a TLeave parameter (new(ELeave)). The macro defines these missing placement delete operators and ensures that all allocated memory can be freed if a constructor leaves.

Related concepts