Made to Order Software Corporation Logo

Pointers and proper exception handling...

Many C++ programmers have been C programmers first. Therefore, a lot of times, you find statements written this way:

ptr = new type;

if(ptr == 0) // handle error...

This is a C programmer that does not yet know that the new operator will throw an error if the allocation cannot happen. This makes a lot of sense, but what does that mean to the C++ programmer?

Note: It is possible to use a new operator that does not throw an error. This is reserved to the highly skilled C++ programmers and those who have to work on software written for low level interfaces such as drivers or embedded code. I will say that if you see such a statement in such a piece of code, it is correct. Do not remove it!

The fact is that if the new operator throws, the statement never returns from the call to the new operator function. This means in the statement ptr = new type; the variable ptr is not going to be changed. In other words, the following class will break in case of a throw in the new statement:

class bad {

    bad() : f_ptr(0) {}

    ~bad() { delete f_ptr; }

    void set(int size) { delete f_ptr; f_ptr = new char[size]; }

};

The set() function deletes the old pointer, then allocate a new one with the right size (assuming you do not need to copy the old buffer). This works until the new throws. If that happens, then the destructor will delete the same pointer a second time since the set() function did not clear the pointer.

The correct set() function would look like this:

  void set(int size) { delete f_ptr; f_ptr = 0; f_ptr = new char[size]; }

In this last example, the pointer is properly handled.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.