The main reason allocate
exists is to allow you to build custom constructors for your objects. As the article you linked mentioned, you can envision the SomeClass.new
method as doing something like the following by default:
class SomeClass
def self.new(*a, &b)
obj = allocate
# initialize is a private instance method by default!
obj.send(:initialize, *a, &b)
end
end
Despite what the documentation says, the existence of the allocate
method is not so much about memory management as it is about providing some finer grained control over the object creation lifecycle. Most of the time, you won't need this feature, but it is useful for certain edge cases.
For example, in the Newman mail framework, I used this technique to implement a fake constructor for a TestMailer object; it implemented the new
method for API compatibility, but actually returned a single instance regardless of how many times it was called:
class Newman::TestMailer
def self.new(settings)
return self.instance if instance
# do some Mail gem configuration stuff here
self.instance = allocate
end
attr_accessor :instance
end
I've not seen many other use cases apart from redefining new
as shown above (although I imagine that some weird serialization stuff also uses this feature). But with that in mind, it's worth pointing out that Ruby consistently provides these kinds of extension points, regardless of whether or not you'll need to use them regularly. Robert Klemme has a great article called The Complete Class which I strongly recommend reading if you want to see just how far this design concept has been taken in Ruby :-)
Marshal
) need to be able to create an object without callinginitialize
sinceinitialize
might do expensive or unnecessary things when you're just going to overwrite everything.