Pointer assignment and exceptions

I've been playing around try/catch blocks and pointers, and I've seen behaviour that I haven't been able to explain so far.
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
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>

using namespace std;

class A
{
    public:
        A()
        {
            cout<<"A init"<<endl;
            showptr();
            cout<<"throwing..."<<endl;
            throw 1;
        }
        ~A()
        {
            cout<<"A deinit"<<endl;
            showptr();
        }

        void showptr()
        {
            cout<<"A "<<this<<endl;
        }
};

class B
{
    public:
        B() : ClassChain(NULL)
        {
            ClassChain = new A;
            cout<<"B init"<<endl;
            showptr();
        }
        ~B()
        {
            cout<<"B deinit"<<endl;
            showptr();
            delete ClassChain;
            ClassChain = NULL;
        }

        A* ClassChain;

        void showptr()
        {
            cout<<"B "<<this<<endl;
        }
};

int main()
{
    B* myClass = NULL;
    try
    {
        myClass = new B;
    }
    //guaranteed throw
    catch(int)
    {
        delete myClass;
        myClass = NULL;
    }
    return 0;
}


The above code causes a segfault at
1
2
3
4
5
~B()
{
    ...
    ClassChain = NULL;
}

Commenting out that line makes the error disappear. From what I've understood from Effective C++, calling delete on an uninitialized or NULL pointer should not be harmful, so I've ruled the preceding line from causing errors.

Can anybody explain why the NULL assignment is causing that error? Is there some rule about pointer assignment during exceptions? Calling the destructor normally in a non-throwing situation doesn't cause the segfault, so I'm kind of confused now.
Are you sure that it is the case? Because nothing should call your destructor in code you provided
If B class constructor throws an exception, assigment to myClass variable will never happen and it will still contain a null pointer. Deleting a null pointer is a no-op by Standard.

Your program is working fine: http://ideone.com/GMGIlc
I made a clean build and now it works fine. Anyway, thanks for taking the time for answering the question, as well as confirming the bit about delete's behaviour.
Last edited on
Topic archived. No new replies allowed.