Fixing C's Biggest Mistake
Max Samukha
maxsamukha at gmail.com
Fri Dec 30 11:08:30 UTC 2022
On Tuesday, 27 December 2022 at 22:53:45 UTC, Walter Bright wrote:
> On 12/27/2022 1:41 AM, Max Samukha wrote:
>> If T.init is supposed to be an invalid value useful for
>> debugging, then variables initialized to that value... are not
>> initialized.
>
> It depends on the designed of the struct to decide on an
> initialized value that can be computed at compile time. This is
> not a failure, it's a positive feature. It means struct
> instances will *never* be in a garbage state.
Yes, they will be in an invalid state.
>
> C++ does it a different way, not a better way.
C++ is looking for a principled solution, as that presentation by
Herb Sutter suggests. By saying "no dummy values", he must be
referring to T.init :)
If you don't want a proper fix as Timon and others are proposing,
can we at least have nullary constructors for structs to be
consistent with the "branding" vs construction ideology?
struct S { this(); }
S x; // S x = S.init;
S x = S(); // S x = S.init; x.__ctor();
There is no reason to require the use of factory functions for
this. Constructors *are* "standard" factory functions.
People have resorted to all kinds of half-working hacks to work
around this in generic code. The latest one I've seen is like:
mixin template Ctors()
{
static typeof(this) opCall(A...)(auto ref A a) {
import core.lifetime: forward;
typeof(this) r;
r.__init(forward!a);
return r;
}
}
struct S
{
// fake ctors
void __init() {}
void __init(...) {}
mixin Ctors;
}
void foo(T)() { T x = T(); } // no need to pass around a factory
function anymore
More information about the Digitalmars-d
mailing list