File: new.cc

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 (52 lines) | stat: -rw-r--r-- 1,295 bytes parent folder | download | duplicates (8)
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
    #include <iostream>
    using namespace std;

    static size_t count = 0;

    class X
    {
        int x;

        public:
            X()
            {
                if (count == 2)
                    throw 1;
                cout << "Object " << ++count << '\n';
            }
            ~X()
            {
                cout << "Destroyed " << this << "\n";
            }
            void *operator new[](size_t size)
            {
                cout << "Allocating objects: " << size << " bytes\n";
                return ::operator new(size);
            }
            void operator delete[](void *mem)
            {
                cout << "Deleting memory at " << mem << ", containing: " <<
                    *static_cast<int *>(mem) << "\n";
                ::operator delete(mem);
            }
    };

    int main()
    try
    {
        X *xp = new X[5];
        cout << "Memory at " << xp << '\n';
        delete[] xp;
    }
    catch (...)
    {
        cout << "Caught exception.\n";
    }
    // Output from this program (your 0x??? addresses might differ)
    //  Allocating objects: 24 bytes
    //  Object 1
    //  Object 2
    //  Destroyed 0x8428010
    //  Destroyed 0x842800c
    //  Deleting memory at 0x8428008, containing: 5
    //  Caught exception.