From: Paul Brannan Date: 2002-05-11T01:35:19+09:00 Subject: Re: freeze and exception safety On Sat, May 11, 2002 at 01:13:35AM +0900, Morris, Chris wrote: > > Is there an exception-safe way that I can freeze sub-objects? > > What about this? Do a deep-clone of your Container, attempt to freeze > everything in the clone, then replace the original with the clone. If an > exception happens before the final assignment, don't do anything, the > half-frozen clone goes away. An interesting idea. Not particularly speedy, but much more safe: class Foo def freeze x_copy = @x.deep_clone # The container must implement deep_clone x_copy.each { |x| x.freeze } x_copy.freeze super @x = x_copy end end Since assignment cannot raise an exception, this should work. However, consider this: class Foo attr_reader :x def initialize @x = Container.new end def freeze # see above end end f = Foo.new x = f.x f.freeze p x.frozen? #=> false There is no good way to replace the original object, because someone else might always be holding a reference to it. Is there a good way around this that doesn't require the co-operation of the user, and will work generically with any container? Paul