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

Steven Schveighoffer schveiguy at gmail.com
Thu Feb 12 18:31:43 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.

`const` as a function attribute applies to the `this` reference. 
If you want a `const` return value, you have to use the type 
constructor form:

```d
const int foo(); // `this` is const, returns mutable int
const(int) foo(); // `this` is mutable, returns const int
const const(int) foo(); // `this` is const, returns const int
const(int) foo() const; // same as above, trailing const applies 
to `this`
```

As shown in the final form, you can apply attributes to `this` 
with a trailing type modifier. You should prefer this form 
because it's clearer when reading.

-Steve


More information about the Digitalmars-d-learn mailing list