File: basic.yo

package info (click to toggle)
c%2B%2B-annotations 13.02.02-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,576 kB
  • sloc: cpp: 25,297; makefile: 1,523; ansic: 165; sh: 126; perl: 90; fortran: 27
file content (54 lines) | stat: -rw-r--r-- 2,474 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
The emi(basic guarantee) dictates that functions that fail to complete their
assigned tasks must return all allocated resources, usually memory, before
terminating. Since practically all functions and operators may throw
exceptions and since a function may repeatedly allocate resources the
blueprint of a function allocating resources shown below defines a try block
to catch all exceptions that might be thrown. The catch handler's task is to
return all allocated resources and then rethrow the exception.
        verb(    void allocator(X **xDest, Y **yDest)
    {
        X *xp = 0;              // non-throwing preamble
        Y *yp = 0;

        try                     // this part might throw
        {
            xp = new X[nX];     // alternatively: allocate one object
            yp = new Y[nY];
        }
        catch(...)
        {
            delete xp;
            throw;
        }

        delete[] *xDest;        // non-throwing postamble
        *xDest = xp;
        delete[] *yDest;
        *yDest = yp;
    })

In the pre-try code the pointers to receive the addresses returned by the
operator tt(new) calls are initialized to 0. Since the catch handler must be
able to return allocated memory they must be available outside of the tt(try)
block. If the allocation succeeds the memory pointed to by the destination
pointers is returned and then the pointers are given new values.

    Allocation and or initialization might fail. If allocation fails tt(new)
throws a hi(bad_alloc)tt(std::bad_alloc) exception and the catch handler
simply deletes 0-pointers which is OK.

    If allocation succeeds but the construction of (some) of the objects fails
by throwing an exception then the following is
    hi(new: and exceptions)hi(exception: and new) em(guaranteed) to happen:
    itemization(
    it() The destructors of all successfully allocated objects are called;
    it() The dynamically allocated memory to contain the objects is returned
    )

    Consequently, there is no memory leak when tt(new) fails. Inside the above
tt(try) block tt(new X) may fail: this does not affect the 0-pointers
and so the catch handler merely deletes 0 pointers. When tt(new Y) fails
tt(xp) points to allocated memory and so it must be returned. This happens
inside the catch handler. The final pointer (here: tt(yp)) will only be
unequal zero when tt(new Y) properly completes, so there's no need for the
catch handler to return the memory pointed at by tt(yp).