Programming in D, page 306. opAssign to return const ref

Brother Bill brotherbill at mail.com
Thu Feb 12 12:55:24 UTC 2026


Near the top of page 306 in Programming in D book, there is this 
note:
*As an optimization, sometimes it makes more sense for* 
```opAssign``` *to return* ```const ref``` *for large structs.*

```
import std.stdio : writeln, writefln;

void main()
{
	auto mms = ManyMembersStruct();
	mms = 42;
}

struct ManyMembersStruct
{
	int  a;
	int  b;
	long c;
	long d;

         // this fails to compile as "const" means that no members 
can be mutated.
	const ref ManyMembersStruct opAssign(int a) {
		this.a = a;
		return this;
	}
}

```

What is the correct way to have opAssign return const ref?
And what does it mean to return const ref?
Please provide a working code sample.


More information about the Digitalmars-d-learn mailing list