File: basic.yo

package info (click to toggle)
c%2B%2B-annotations 8.2.0-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 11,804 kB
  • ctags: 2,845
  • sloc: cpp: 15,418; makefile: 2,473; ansic: 165; perl: 90; sh: 29
file content (55 lines) | stat: -rw-r--r-- 2,487 bytes parent folder | download
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
55
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 retrow 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, no memory will leak when tt(new) fails. Inside the above
tt(try) block tt(new X) may fail: this will keep the 0-pointers intact and so
the catch handler merely deletes 0 pointers. When tt(new Y) fails tt(xp) will
point 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).