Disagreeing addresses of `this`

Nick Treleaven nick at geany.org
Sun May 12 21:09:33 UTC 2024


On Sunday, 12 May 2024 at 13:03:35 UTC, Longinus wrote:
> So my understanding is that structs have an implicit `opAssign` 
> which takes its argument by value, and that it only calls the 
> destructor on its own copy, but not that of the argument, which 
> may be a temporary.

Not sure if it helps, but...

This is the low-level code (`dmd -vcg-ast`):
```d
	ref @system S opAssign(S p) return
	{
		(S __swap40 = void;) , __swap40 = this , (this = p , 
__swap40.~this());
		return this;
	}
```

> For example:
> ```d
> struct S
> {
>     this(int x) { writeln("ctor ", &this); }
>     ~this()     { writeln("dtor ", &this); }
> }
> void main()
> {
>     S s;
>     writeln("main ", &s);
>     s = S(42);
> }
> ```
> the result, when compiled with DMD, is
> ```
> main 7FFF28396290

`main.s`

> ctor 7FFF28396291

Temporary `S(42)` is constructed on main's stack, passed as 
argument `p` to `opAssign`. Then:

* `main.s` is bit-copied to `__swap40`.
* `p` is then bit-copied to `main.s`.

> dtor 7FFF28396268

`__swap40.~this()` inside `opAssign`.

> dtor 7FFF28396290

`main.s.~this()` at the end of `main`.


More information about the Digitalmars-d mailing list