Programming in D page 295 - disable default constructor
H. S. Teoh
hsteoh at qfbox.info
Tue Feb 10 15:39:45 UTC 2026
On Tue, Feb 10, 2026 at 01:23:43PM +0000, Brother Bill via Digitalmars-d-learn wrote:
[...]
> My question is about the *parameterless* constructor:
> ``` auto a4 = Archive();```
>
> I am unable to define a parameterless constructor for it.
This is by design. Structs cannot have parameterless (default) ctors.
Creating a struct using `S()` gives you a copy of S.init.
> Is the only alternative to prevent a parameterless construction to use
> ```@disable this();``` ?
Rather than fighting with the type system, I recommend redesigning your
type such that the .init value of your struct is either a valid
instance, or else a well-known sentinel value that can be easily checked
for validity. While there are various ways of working around it, the
result often has troublesome corner case behaviours (such as interacting
badly with generic code, including parts of Phobos) that makes it not
worth the effort.
Structs in D were designed to behave like "glorified ints", i.e.,
POD-like aggregates with trivial initialization, by-value semantics,
cheap copying, and simple, int-like behaviour. Of course, since then
several complex idioms have developed around structs, but nonetheless,
things work most smoothly when you use them in accordance with the
concept of them being "glorified ints". If you want complex default
construction, polymorphic behaviour, or by-reference semantics, consider
using classes instead.
T
--
People demand freedom of speech to make up for the freedom of thought which they avoid. -- Soren Aabye Kierkegaard (1813-1855)
More information about the Digitalmars-d-learn
mailing list