Why does this call the copy constructor 2 times and the assigment constructor once?
Paul Backus
snarwin at gmail.com
Fri Nov 19 14:22:07 UTC 2021
On Friday, 19 November 2021 at 14:05:40 UTC, rempas wrote:
> So, when I assign the value of the variable "name" in the
> "other_name", first it will call the copy constructor, then it
> will call the assignment constructor and then it will call the
> copy constructor again. Why is this happening? I was expecting
> only the assignment constructor to get called.
When you pass a struct instance to a function by value, or return
a struct instance from a function by value, a copy is made, and
the copy constructor is called.
Your `opAssign` takes `rhs` by value, and returns a `str` by
value:
```d
// Returned by value
// |
// v
str opAssign(str rhs) {
// ^
// |
// Passed by value
```
So, every call to it will result in two calls to `str`'s copy
constructor.
If you want to avoid this, you can change `opAssign` to have the
following signature:
```d
// Returned by referece
// |
// v
ref str opAssign()(auto ref str rhs)
// ^
// |
// Passed by reference (if possible)
```
Since `auto ref` is only allowed for template functions, I have
added an empty template argument list (the `()`) to make
`opAssign` into a function template.
You can read more about [`ref` functions][1] and [`auto ref`
parameters][2] in the D language specification.
[1]: https://dlang.org/spec/function.html#ref-functions
[2]: https://dlang.org/spec/template.html#auto-ref-parameters
More information about the Digitalmars-d-learn
mailing list