Partially constructed objects in various languages

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Aug 23 13:39:05 PDT 2013


On Tue, Aug 20, 2013 at 04:55:21AM +0200, bearophile wrote:
> Perhaps this thread deserves a D implementation with a small
> explanation regarding D:
> 
> http://www.reddit.com/r/programming/comments/1kof0q/on_partiallyconstructed_objects/
> 
> (__ctWriteln is not yet available in D.)
[...]

One issue he brought up that he didn't really address, was what to do if
a ctor throws before fully initializing all fields. For example:

	class A { ~this() { ... } }
	class B { ~this() { ... } }
	class C {
		A a;
		B b;
		this() {
			a = new A();
			if (someCondition)
				throw new Exception(...);
			b = new B();
		}
	}

The problem is, how would the compiler know to call A.~this, but not
B.~this when the Exception is thrown?

Also, the whole deal with partially-constructed objects seems to be
related to a recent thread about encapsulating ctor parameters and
objects being created first then kicked into shape (create-set-call
pattern) vs. passing everything to the ctor in one go (long ctor
argument list).

It seems ultimately to boil down to recognizing that there's a
transition point between an object's creation and its reaching a
fully-valid initial state. Before this transition takes place, the
object is in a partially-constructed state, and may violate class
invariants. At the transition point, the ctor (or whatever's responsible
for turning the object into a fully-constructed state) verifies that all
constraints are met, before the object is regarded as a full instance of
its class. This seems reminiscient of Perl's approach of creating an
object as a normal hash, then "bless"ing it into a full-fledged class
instance once it's fully initialized.


T

-- 
Long, long ago, the ancient Chinese invented a device that lets them see through walls. It was called the "window".


More information about the Digitalmars-d-learn mailing list