May 10, 2018
A discussion came up on Reddit about C++'s initializer lists, and I realized I didn't really know what other languages in the same space do for member initialization. I'm not looking to start a language war here; I'm asking out of curiosity/general knowledge.

I found a prior discussion on what D does [1], and I think the most relevant part is this (reduced slightly from the original):

>    class MyClass {
>        int d = 6;
> 
>        this(int val) {
>            d = val;
>        }
>    }
>
>
> You are correct that in the case of the [...] constructor,
> two assignments effectively take place, d = 6, then d = 7.


In C++ terms, I would describe this as "d is first initialized to 6, and then assigned to from 7".

However, if that's the only mechanism for "initializing" a class variable it seems to me like this would cause problems with:

* Classes that can't be default-initialized because they need some data to be provided
  not known until runtime and it is desired that there not be a way to construct an
  "empty" object; something like this C++:

    class Person {
       string name;

       // no Person() provided
       Person(string n) { n = name; } // not "idiomatic c++", but works
    };

    class EmployeeRecord {
       Person person;

       // no this() provided
       EmployeeRecord(string name) : person(name) {} // no way to *not* use init-list
    };

* Classes that can't be assigned. I'm having a harder time coming up with a good
  example here that would usefully be a member of another class, but some RAII
  objects could fit the bill. (For example, std::lock_guard is not copyable or
  assignable.)


How would these be handled in D? Do these concepts exist in some form? If so, how would you initialize them?

Evan


[1] https://forum.dlang.org/thread/jg9ajr$1iaq$1@digitalmars.com