Jan 31, 2009

When you use the new operator, there are three steps: allocate a portion of memory where the new class is going to be instantiated, instantiate the cl

When you use the new operator, there are three steps: allocate a portion of memory where the new class is going to be instantiated, instantiate the class on that memory, and assign that memory location to a variable.
Class* p = new Class;
New can throw an exception (out of memory). In this case, no memory is allocated. The variable p is not assigned a new value.
New calls the constructor of the class. The constructor can throw an exception. If class has any base classes or member objects, the constructors for each are called before the constructor for class.
If an exception is thrown in the body of Class's constructor, destructors are called for all those base and derived classes for which the constructor has already been called (cleaning those objects up). The destructor for Class is NOT called (as indicated by blank above).
Finally, memory allocated by new is freed and p is not assigned a value.
What this means in practical terms, is that classes should use smart pointers to wrap resources in classes to ensure proper cleanup.

No comments:

Post a Comment