Re: Free allocated memory
Roland Pibinger wrote:
On 30 Jun 2006 11:55:09 -0700, "mlimber" <mlimber@gmail.com> wrote:
Roland Pibinger wrote:
On 30 Jun 2006 10:50:15 -0700, "mlimber" <mlimber@gmail.com> wrote:
Returning dynamically allocated objects from a function is a common and
useful thing
In Java yes, but not in C++.
Are you kidding me? Factory functions are a common design pattern. See
guru Sutter's example under "sources and sinks" here:
http://www.gotw.ca/publications/using_auto_ptr_effectively.htm
"Avoid using auto_ptr, instead use shared_ptr"
(http://www.gotw.ca/publications/). Things change when you take a
closer look at smart pointers ...
Take a look at the history of the standard library's smart pointers
here:
http://boost.org/libs/smart_ptr/smart_ptr.htm#History
Originally, counted_ptr and auto_ptr (which had the semantics of
shared_ptr and scoped_ptr, respectively) were proposed for inclusion in
the library, but the Library Working Group's recommendation was
over-ruled, counted_ptr was dropped and the copy semantics for auto_ptr
were changed (most think for the worst). Sutter is merely advocating
the original approach, which experience has shown is generally better.
And see the virtual constructor idiom in the FAQ:
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8
Circle* Circle::clone() const { return new Circle(*this); }
Returns the ownership of a resource to the caller, an anti-idiom.
I would certainly return a smart pointer rather than a bald pointer,
but that is not the point of the example. (Compare Stroustrup's FAQs on
memory leaks and virtual constructors.)
Apart from that I agree with Howard's position. There are two secrets
of resource management:
1. don't return a resource (not even as "smart" pointer);
That's your rule, not generally accepted C++ wisdom.
A rule that mostly eliminates the troubles with resource management.
Again, the advice of the C++ gurus is entirely against you.
2. release resources in the destructor (if not done before) of a
containing object
That's RAII, and it's the same technique auto_ptr uses.
There is a difference which can be described as deterministic vs.
non-deterministic resource management. The destruction of a returned
smart pointer like auto_ptr is non-deterministic.
I don't follow you here.
(and allocate the resources in a member function of that object).
That's unnecessary.
It 'only' encapsulates allocation and deallocation of resources, ie.
resource management.
Don't misunderstand me. It's a good principle to encapsulate
construction and destruction in a class when possible (that's what
containers like std::vector do, after all), but it is not always
possible, e.g., when you're using an object polymorphically and the
concrete type of the object is not known until run-time. That's a
common place to use a factory function, as mentioned above.
Cheers! --M