Assigning &this in constructor.

pineapple via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 18 15:43:29 PST 2017


On Wednesday, 18 January 2017 at 23:08:07 UTC, Adam D. Ruppe 
wrote:
> On Wednesday, 18 January 2017 at 22:57:22 UTC, NotSpooky wrote:
>> Is it undefined behavior to assign &this to a pointer in the 
>> constructor of a struct?
>
> Yes:
>
> http://dlang.org/spec/struct.html
> "A struct is defined to not have an identity; that is, the 
> implementation is free to make bit copies of the struct as 
> convenient."
>
> That means it might copy and/or move it without giving you a 
> chance to update the pointer. Updating in postblit can help 
> sometimes but still the compiler and library are allowed to 
> move structs without notice.

Practically speaking I've found that if the struct was allocated 
on the heap, then &this acquires that pointer and seems not to 
break anything, e.g. how it's used in the uncopyable struct here 
https://github.com/pineapplemachine/mach.d/blob/master/mach/collect/linkedlist.d#L165


More information about the Digitalmars-d-learn mailing list