Ivan Liu wrote:
Quote:
I'd like to know if I declare and initialise a reference as the
following:
>
MyClass & rA = *( new MyClass( my_arguements) );
>
at the end of the routine will the memory containing the object, which
rA refers to, be freed?
By "end of routine" I presume you mean "end of scope", and the answer
is "No, you must delete it." However, in general, you should use a
smart pointer (e.g., std::auto_ptr, std::tr1::shared_ptr aka
boost::shared_ptr) or a container (see
http://www.parashift.com/c++-faq-lit....html#faq-34.1) instead
of manually managing memory anyway. They can be free of overhead and
provide exception safety as well as automatic clean-up.
Quote:
Alternatively I would first declare a pointer and then at the end
delete
the pointer, like:
>
MyClass * pA = new MyClass( my_arguements);
MyClass & rA = *pA;
>
delete pA;
Unlike your code above, this will not produce a memory leak.
Cheers! --M