TITLE: New/delete versus using local variables


PROBLEM: rcromw1@umbc.edu (Ray Cromwell)

Sometimes, I see people do this in code

func()
{
    Object *o=new Object(blah);
    // use o
     delete o; // hopefully
}

whereas I always use
func()
{
    Object o;
    // use o
}

   Furthermore, for functions which must return a resource structure,
I see this in a lot of code:

   Object *o;
   o=retrieve_object(key);

 where retrieve_object allocates the object and fills in the neccessary
fields (usually there is a dispose_object(o) call too)

   However, I have been using this construct:

   Object o;
   retrieve_object(key, o); // this function takes a reference to Object

   Here, retrieve_object fills in the fields of object o after it has
been constructed by the default constructor (which usually does nothing)


[ Using local variables instead of heap-allocation is a superior
  coding style under many circumstances. Beginning C++ programmers
  typically make the mistake of using the allocate/deallocate version
  of func().

  The first form of retrieve_object() has the deficiency of burdening
  client code with the responsibility for deleting an object it did
  not allocate.

  Note that retrieve_object() takes an Object BY REFERENCE, not
  by value.

  -adc ]

