Fixing C's Biggest Mistake

Max Samukha maxsamukha at gmail.com
Tue Jan 3 10:13:42 UTC 2023


On Monday, 2 January 2023 at 22:53:30 UTC, Walter Bright wrote:
> On 12/31/2022 2:28 AM, Max Samukha wrote:
>> For types that require runtime construction, initializing to 
>> T.init does not result in a constructed object.
> The idea is to:
>
> 1. have construction that cannot fail. This helps avoid things 
> like double-fault exceptions

I understand the idea. My point (again) is that an object 
initialized to a dummy value is not a constructed object. Yes, 
the dummy value is better than random garbage. However, you 
cannot say "construction cannot fail". An object initialized to a 
dummy value has not been constructed. You have deferred 
construction to a later point, and it may fail there. Lazy 
initialization, initialization in factory functions, etc. is 
nothing but deferred construction.

Please take a look at C#. They rightfully distinguish 
`default(T)` (their equivalent of `T.init`) from `T()`. From 
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct#struct-initialization-and-default-values:
"That creates a distinction between an uninitialized struct, 
which has its default value and an initialized struct, which 
stores values set by constructing it."

See, they don't pretend that "set to default value" is 
"initialized"?

>
> 2. have initializers that can be placed in read only memory

That seems to be irrelevant to my argument. Fully constructed 
objects can be serialized to ROM as well.

>
> 3. have something to set a destroyed object to, in case of 
> dangling references and other bugs

Yes, the object is set to the dummy state before construction and 
after destruction. Constructors are for construction. `this()` is 
a constructor. Just unban it.

>
> 4. present to a constructor an already initialized object. This 
> prevents the common C++ problem of adding a field and 
> forgetting to construct it in one of the overloaded 
> constructors, a problem that has plagued me with erratic 
> behavior

`this()` is a constructor - present to it the default-initialized 
object just as you do to other constructors.

>
> 5. provide a NaN state. I know many people don't like NaN 
> states, but if one does, the default construction is perfect 
> for implementing one.

That is irrelevant to my point. I am not arguing against default 
initialization. Just don't call it construction. Constructors 
replace the dummy value with a useful one.

>
> 6. it fits in well with (future) sumtypes, where the default 
> initializer can be the error state.

No objection.

>
> An alternative to factory functions is to have a constructor 
> with a dummy argument. Nothing says one has to actually use the 
> parameters to a constructor.

I know about the dummy argument hack. I just see no reason why I 
have to do that.


More information about the Digitalmars-d mailing list