struct parameterless constructor
H. S. Teoh
hsteoh at qfbox.info
Tue Aug 5 23:23:44 UTC 2025
On Tue, Aug 05, 2025 at 03:27:06AM -0600, Jonathan M Davis via Digitalmars-d-learn wrote:
> On Monday, August 4, 2025 5:21:53 PM Mountain Daylight Time H. S. Teoh via Digitalmars-d-learn wrote:
> > Fast forward 20 or so years, and things have changed a bit. People
> > started using structs for many other things, some beyond the
> > original design, and inevitably ran into cases where they really
> > needed parameterless default ctors for structs. But since the
> > language did not support this, a workaround was discovered: the
> > no-op default ctor that the compiler generates for each struct
> > (i.e., this()), was tagged with @disable, which is a mechanism to
> > indicate that the initial by-value blit of the struct is *not* a
> > valid initial state. Then opCall was used so that you could
> > construct the struct like this:
> >
> > auto s = S();
> >
> > which resembles default construction for class objects, at least
> > syntactically. This wasn't in line with the original design of the
> > language, but it worked with current language features and got
> > people what they wanted without further language changes, so it was
> > left at that, and became the de facto standard workaround for the
> > language's lack of default struct ctors.
>
> I know that this advice has been given plenty of times the past, but
> I'd actually strongly advise against ever doing this.
[...]
I agree, fighting against the way the language is designed inevitably
leads to trouble. It may work on the surface but you start running into
one bad case after another, and it all just goes downhill from there.
Better to use the language as it's intended to be used instead.
I've seen Phobos bugs that were ultimately caused by using @disable
where it wasn't intended. All kinds of special cases had to be
introduced to uglify the code to handle these exceptional cases, often
at the expense of the regular code path. Alias this is another of these
things that looked clever at the time, but in retrospect were
misfeatures.
T
--
If you want to solve a problem, you need to address its root cause, not
just its symptoms. Otherwise it's like treating cancer with Tylenol...
More information about the Digitalmars-d-learn
mailing list