C + + Pure manual memory management, is indeed a source of all evils. There is a well-known memory leak problem in the construction of the object. For example, a class is as follows:
class A
{
public:
A()
{
a1 = new T1();
a2 = new T2();
...
an = new Tn();
}
private:
T1 * a1;
T2 * a2;
...
Tn * an;
}
When you call new A () for allocation, failure can lead to memory leaks. For example, the system is Chi Chi assigned to the A18, failed, throw an exception, or return null value, the front A1-a17 object, completely became no Niang tube of the baby, and leaked out. A solution strategy is to manage each assigned object, and if there is a problem, clear everything. For example, A18 allocation failed, delete a1-a17. And don't say there are other problems, but this coolie, it is estimated that not many people can afford.
Two-stage construction
To solve the problem of object allocation, Symbian pondered the so-called two-stage construction method, which is a pattern that separates the initialization of stack data from the allocation process of the heap objects. A standard two-phase construction class is as follows:
class A
{
public:
~A();
static A * NewL();
static A * NewLC();
private:
A();
void ConstructL();
}
The content is available in every Symbian C + + class that is automatically constructed. In a constructor, you can only perform assignments, such as initializing the contents of the stack, and the entire operation does not involve the allocation of objects in the heap. All the objects in the heap that need to be allocated are deferred to the CONSTRUCTL function. NEWL and NEWLC provide a package that encapsulates the constructor and the two-phase constructor. Of course, only in this way, can not solve the problem of memory leaks, a core mechanism is to clean the stack, that is, Cleanupstack.