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

monkyyy crazymonkyyy at gmail.com
Thu Feb 12 17:53:09 UTC 2026


On Thursday, 12 February 2026 at 12:55:24 UTC, Brother Bill wrote:
> 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.

I consider it a delusion, but Im pretty sure that the author 
believes in immutable data structures, either make a linked list 
or a handle of some kind.

Its non-trivial to find a case that actually would work and have 
reasonable array-like speeds. And I do believe near impossible to 
show a situation where compiler optimizations + arrays lose to 
your book keeping on real speed tests


More information about the Digitalmars-d-learn mailing list