struct constructors and destructors.

via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 20 03:25:31 PDT 2017


On Thursday, 20 July 2017 at 09:09:42 UTC, Danni Coy wrote:
> On Thu, Jul 20, 2017 at 12:19 AM, SrMordred via Digitalmars-d < 
> digitalmars-d at puremagic.com> wrote:
>
>> On Wednesday, 19 July 2017 at 14:09:32 UTC, SrMordred wrote:
>>
>>> On Wednesday, 19 July 2017 at 09:09:40 UTC, Stefan Koch wrote:
>>>
>>>> On Wednesday, 19 July 2017 at 07:48:28 UTC, Danni Coy wrote:
>>>>
>>>>> Is there a reason that the following code
>>>>>
>>>>> struct Foo
>>>>> {
>>>>>     this (string name)
>>>>>     { do_something(name); }
>>>>>
>>>>>     ~this()
>>>>>     { undo_something(); }
>>>>> }
>>>>>
>>>>> Foo foo = void;
>>>>>
>>>>> void open()
>>>>> {
>>>>>     foo = Foo("test"); // <- this line
>>>>> }
>>>>>
>>>>> tries to OpAssign foo to itself then calls foo's destructor?
>>>>>
>>>>
>>>> What happens is this.
>>>>
>>>> void open()
>>>> {
>>>>   foo = () {
>>>>   Foo _tmp = Foo.__ctor("test");
>>>>   return _tmp;
>>>>   } ();
>>>> }
>>>>
>>>
>>> Hm, isnt that wrong?
>>> If I destroy resources on the dtor, wouldn't it invalidate 
>>> the resource
>>> on the copy?
>>> Also, C++ behaves differently
>>>
>>
>> No Sorry, it behaves almost the same.
>> just in D ctor and dtor are not called on declaration even if 
>> you drop " =
>> void".
>>
>
> Is there a way to delay the initialisation of a struct?

void initialization + emplace:

struct Foo
{
     this (string name)
     { create_count++; }

     ~this()
     { destroy_count--; }
}

int create_count;
int destroy_count;
Foo foo = void;

void main()
{
     import std.stdio;
     import std.conv : emplace;

     writefln("this(string) ran %s times.", create_count);
     writefln("~this() ran %s times.", destroy_count);

     emplace(&foo, "test");
     writeln("--- emplace ---");

     writefln("this(string) ran %s times.", create_count);
     writefln("~this() ran %s times.", destroy_count);
}

this(string) ran 0 times.
~this() ran 0 times.
--- emplace ---
this(string) ran 1 times.
~this() ran 0 times.

https://is.gd/G06GvK


More information about the Digitalmars-d mailing list