Symbian3/SDK/Source/GUID-1FFE4ED5-7B2E-58A0-9D08-A096F53F37AB.dita
author Dominic Pinkman <dominic.pinkman@nokia.com>
Tue, 20 Jul 2010 12:00:49 +0100
changeset 13 48780e181b38
parent 0 89d6a7a84779
permissions -rw-r--r--
Week 28 contribution of SDK documentation content. See release notes for details. Fixes bugs Bug 1897 and Bug 1522.

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2007-2010 Nokia Corporation and/or its subsidiary(-ies) All rights reserved. -->
<!-- This component and the accompanying materials are made available under the terms of the License 
"Eclipse Public License v1.0" which accompanies this distribution, 
and is available at the URL "http://www.eclipse.org/legal/epl-v10.html". -->
<!-- Initial Contributors:
    Nokia Corporation - initial contribution.
Contributors: 
-->
<!DOCTYPE concept
  PUBLIC "-//OASIS//DTD DITA Concept//EN" "concept.dtd">
<concept xml:lang="en" id="GUID-1FFE4ED5-7B2E-58A0-9D08-A096F53F37AB"><title>Object Lifetimes and Cleanup</title><prolog><metadata><keywords/></metadata></prolog><conbody><p>Object lifetime is a fundamental concept. This topic contains a summary of object lifetime idioms in Symbian platform C++. </p> <section><title>Overview</title> <p>In some operating systems, the object lifetime can be neglected, because the stack and heap are destroyed when a program terminates. On the Symbian platform, programs may run for months. It is therefore important that objects be cleaned up as soon as their lifetime ends, whether they are allocated on stack or heap, and whether their lifetime ended through normal processing or through an error condition. </p> <p>On both stack and heap, objects have a lifetime that runs approximately as follows: </p> <ol id="GUID-0CF65C93-161A-5E6A-A41A-E3360122D8EB"><li id="GUID-092C9503-16F6-546F-BEBE-2B0D7BE3D13C"><p>allocate memory for the object [on stack or heap] </p> </li> <li id="GUID-07E6B1C2-ABE4-527A-A34B-E391A79AE6DE"><p>initialise: i.e., set the contents of that memory to usable values </p> </li> <li id="GUID-80B1C90A-B26A-59E2-B8C1-6262DD1C1E13"><p>use the object </p> </li> <li id="GUID-74A5297F-CD48-5C64-BFBE-10A2A1930147"><p>clean up: i.e., free up any other resources that might have been used by that object </p> </li> <li id="GUID-16D4FDD6-0E2F-57BE-A17C-E2AC31E8EE86"><p>de-allocate memory [from stack or heap] </p> </li> </ol> </section> <section><title>Lifetimes in C</title> <p>On the C stack, an object’s lifetime, for a user of that object, might look like this: </p> <codeblock id="GUID-B725D30E-0EF9-592A-A2B8-5B15D5E8C122" xml:space="preserve">#include "s.h"</codeblock> <codeblock id="GUID-28EFD521-310D-5EC8-A4F1-EA56D6A74A14" xml:space="preserve">void foo()
    {
    S s;
    sInitialize(&amp;s, p1,p2);
    sUse(&amp;s, p3,p4);
    sCleanup(&amp;s);
    }</codeblock> <p>Memory for the <codeph>S</codeph> is allocated on entry to the function, and de-allocated on exit. The functions <codeph>sInitialize()</codeph> and <codeph>sCleanup()</codeph> have been defined as part of the API for an <codeph>S</codeph>, in <filepath>s.h</filepath> (in fact, C programmers are not always as disciplined as this, and expect the users of their objects to do their own initialisation, in an ad hoc way). The function <codeph>sUse()</codeph> represents a use of the <codeph>S</codeph>. Note that the <codeph>S</codeph> is passed by pointer: its address must be taken whenever it is used as a function parameter. </p> <p>On the C heap, an object's lifetime might look like this: </p> <codeblock id="GUID-93293B5E-C266-529F-8237-5A3FCAF55238" xml:space="preserve">void foo()
    {
    S* s=(S*)malloc(sizeof(S));
        // should really check this succeeded!!
    sInitialize(s, p1,p2);
    sUse(s, p3,p4);
    sCleanup(s);
    free(s);
    }</codeblock> <p>This time, a pointer is used to refer to the <codeph>S</codeph>: as a result, the syntax of passing an <codeph>S</codeph> is slightly more pleasant, because you don’t have to take its address. </p> <p>On the other hand, the allocation and de-allocation of memory is done using <codeph>malloc()</codeph>, whose syntax is extremely ugly, and <codeph>free()</codeph>. </p> <p>Mostly, the lifetime of a heap-based object would not be contained within a single function like this: it might be created from one function, used from another, and destroyed from another. </p> </section> <section><title>Lifetimes in C++</title> <p>One way of looking at C++ is as a neat way to control object lifetimes. C++ allows functions to be associated directly with objects, which means that you do not need a special naming convention to indicate that a function is loosely associated with an object. Two special functions are the constructor and the destructor: the constructor is called every time the C++ system knows that an object’s lifetime begins, and the destructor is called every time the C++ system knows that an object’s lifetime ends. Finally, C++ defines <codeph>operator new()</codeph>, which is much nicer than <codeph>malloc()</codeph>, and <codeph>operator delete</codeph>, which is somewhat nicer than <codeph>free()</codeph>. </p> <p>On the C++ stack, an object’s lifetime looks like this: </p> <codeblock id="GUID-F71A9ED7-B9D4-5C23-B4C6-0A7CED45B0F1" xml:space="preserve">void foo()
    {
    S s(p1,p2); // invokes constructor
    s.Use(p3,p4); // nice syntax!
    } // invokes destructor</codeblock> <p>Memory is allocated on function entry, and the constructor is invoked when processing reaches the declaration. The use of member functions makes the syntax of using everything much more pleasant: there is no need to pass a reference to the <codeph>S</codeph>, because that is done implicitly. </p> <p>Crucially, C++ causes the destructor to be invoked when the function terminates. There is no need for the user of the class to do anything to cause this to happen — all that’s necessary is that the provider of the class provided a destructor. </p> <p>Note, though, that in some exception conditions — for instance, if the <codeph>Use()</codeph> function fails in some way — the function may not return normally, and the destructor will therefore not be invoked. We will shortly discuss how the Symbian platform addresses this. </p> <p>On the C++ heap, object lifetime looks like this: </p> <codeblock id="GUID-E2998E56-C725-567A-845E-F3BD4D5AEB26" xml:space="preserve">void foo()
    {
    S* s=new S(p1,p2); // allocate, construct - should really check
    s-&gt;Use(p3,p4);
    delete s; // destruct, de-allocate
    }</codeblock> <p>Again, the syntax is much nicer. Only one thing cannot be provided by C++: the user of a class must still remember to delete the object at the end of its lifetime. </p> </section> <section><title>Lifetimes in Symbian</title> <p>Symbian platform idioms for object lifetime on the stack look very similar to standard C++. The control of object lifetimes on the heap is, however, very different, as shown in the following code: </p> <codeblock id="GUID-F43C60C2-DA07-56B2-9F49-35ED3AA8A9C8" xml:space="preserve">void FooL()
    {
    CS* s=new (Eleave) CS; // allocate and check
    CleanupStack::PushL(s); // push, just in case
    s-&gt;ConstructL(p1,p2);    // finish constructing - might leave
    s-&gt;UseL(p3,p4); // use - might leave
    CleanupStack::PopAndDestroy();    // destruct, de-allocate
    }</codeblock> <p>This code fragment shows four vital things: </p> <ul><li id="GUID-AB53EB00-02A6-5792-99F1-CD1936D1D4FE"><p>all heap-based classes have names beginning with <codeph>C</codeph>: they are in fact derived from a single base class, <codeph>CBase</codeph>, which exists solely to support easy cleanup </p> </li> <li id="GUID-F9AE98B6-73B4-5367-8896-72E155DA3CAF"><p>a cleanup stack is used to hold references to objects: if a leave occurs due to out-of-memory or some other error, objects held on the cleanup stack are popped from it, and destroyed. In the case of <codeph>CBase*</codeph> objects pushed to the stack, they are destroyed by calling their C++ destructor. The <codeph>CBase</codeph> class has a virtual destructor (<codeph>CBase::~CBase()</codeph>) which makes this possible. </p> </li> <li id="GUID-3D6958DA-9B6C-5E31-BE3A-A6A53A6F3E5A"><p>any function which might leave is designated by a trailing <codeph>L</codeph> in its name. When you see a function that might leave, you must <i>always</i> ask what would happen if it did leave, and what would happen if it did not. The operating system provides all the program infrastructure required to allow objects to be de-allocated even when a leave occurs, but without burdening the programmer. </p> </li> <li id="GUID-AE0B0553-E708-5172-A0B8-A5D366EDAF5D"><p> <codeph>new (ELeave)</codeph> is an overloaded <codeph>operator
                new()</codeph> function, which will leave if it fails to allocate the required memory. It never returns a null pointer. </p> </li> </ul> <p>Two other things are worthy of note: </p> <ul><li id="GUID-36F6B5B6-0772-5656-8C6F-04DD9477F53F"><p>since the cleanup stack itself requires memory allocation for each stack frame, a push might leave. The <codeph>PushL()</codeph> function reflects this in its name. The cleanup stack is guaranteed to have a free slot before a <codeph>CleanupStack::PushL()</codeph>, so that the object reference will always be successfully stored on the stack. If a leave occurs when allocating the next stack frame, the object will be popped and destroyed as normal. </p> </li> <li id="GUID-2825BDD3-28BB-5005-8216-9B3617289326"><p> <i>the C++ constructor must not leave</i>. For objects whose construction requires resource allocation or any other operation that might fail, this means that construction must be separated into a C++ constructor that does not leave, and another initialisation function that might leave, which is conventionally called <codeph>ConstructL()</codeph>. </p> </li> </ul> <p>The cleanup stack, <codeph>CBase</codeph>, and two-phase construction, are at the heart of the operating system. A very few rules govern cleanup stack programming, and they are relatively easy to learn. See <xref href="GUID-E7D29464-05E1-5039-8A02-62CB27B5FF21.dita">Cleanup Stack Basics</xref> for more on this. </p> </section> </conbody></concept>