Would love to override default ctor of struct
Meta
jared771 at gmail.com
Tue Jan 22 03:30:34 UTC 2019
On Tuesday, 22 January 2019 at 01:18:24 UTC, aliak wrote:
> On Monday, 21 January 2019 at 20:50:45 UTC, Meta wrote:
>> On Monday, 21 January 2019 at 19:08:49 UTC, Alex wrote:
>>> Could you give an example, where a zero argument construction
>>> has to be done, which cannot be accomplished by setting the
>>> appropriate field with a default value?
>>
>> For the following reason, although the default argument
>> constructor hack no longer works:
>>
>> import std.stdio;
>>
>> struct Test(bool useFieldDefaultVal)
>> {
>> static if (useFieldDefaultVal)
>> {
>> int[] arr = [1, 2, 3];
>> }
>> else
>> {
>> int[] arr;
>>
>> this(int dummy = 0)
>> {
>> arr = [1, 2, 3];
>> }
>> }
>>
>> void doTest()
>> {
>> writeln("Address of arr: ", arr.ptr);
>> }
>> }
>>
>> void main()
>> {
>> Test!true t1;
>> Test!true t2;
>>
>> // Deprecation: constructor
>> `onlineapp.Test!false.Test.this`
>> // all parameters have default arguments, but structs
>> cannot
>> // have default constructors.
>> auto t3 = Test!false();
>>
>> t1.doTest(); // Prints "Address of arr: 5622DAA0F010"
>> t2.doTest(); // Prints "Address of arr: 5622DAA0F010"
>> t3.doTest(); // Prints "Address of arr: null"
>> }
>
> Ok, so this confused me a bit, I seem to remember that when you
> static inisialize a class in the declaration scope of a struct,
> the same thing would happen as with arrays, i.e. they'd have
> the same address. But this turned out different:
>
> import std.stdio;
>
> class C {}
>
> struct Test(bool useFieldDefaultVal)
> {
> static if (useFieldDefaultVal)
> {
> C c = new C;
> }
> else
> {
> C c;
>
> this(int dummy = 0)
> {
> c = new C;
> }
> }
>
> void doTest()
> {
> writeln("Address of c: ", &c);
> }
> }
>
> void main()
> {
> Test!true t1;
> Test!true t2;
>
> // Deprecation: constructor `onlineapp.Test!false.Test.this`
> // all parameters have default arguments, but structs cannot
> // have default constructors.
> auto t3 = Test!false();
>
> t1.doTest(); // Prints "Address of arr: 7FFE1322A7E8"
> t2.doTest(); // Prints "Address of arr: 7FFE1322A7F0"
> t3.doTest(); // Prints "Address of arr: 7FFE1322A7F8"
> }
>
> t1 and t2 have different addresses and t3 has t1's address??
> Huh?
>
> Vat Khappened Khere?
You're printing the address of the object reference, not the
object itself (similar to printing the address of a pointer
instead of the actual address it points to). Do `cast(void*)c`
instead.
More information about the Digitalmars-d
mailing list