Why is this code error prone

This code i came while reading Stroustrop website. Couldn't understand why he mentioned this code as error prone!


http://www.stroustrup.com/bs_faq2.html#delete-scope

1
2
3
4
5
6
	void fct()	// ugly, error-prone, and inefficient
	{
		X* p = new X;
		// use p
		delete p;
	}
Line 3 results in a possible exception because memory is unavailable. If any exception occurs on line 4, *p will not be destroyed and the memory pointed to by p will be leaked. It's easy enough to forget line 5.

In other words, there are lots of opportunities for error to creep in. Whereas with:
1
2
3
4
5
    void fct()
    {
        X p ;
        // use p
    }

many of those opportunities for error do not exist.
he mentioned
"Code that creates an object using new and then deletes it at the end of the same scope is ugly, error-prone, and inefficient"

If the object is huge, if i want create on the heap then delete in the same function is it wrong?
This code is error prone compared with smart pointers. It does not guarantee that the pointer will be deleted while smart pointers do guaratee this.
Topic archived. No new replies allowed.