5 ms·
When I learned about copy elision, I learned about it in the context of learning about RVO, which is a special case in C++. Otherwise I had no reason to general
by CyberRabbi 6y ago
When I learned about copy elision, I learned about it in the context of learning about RVO, which is a special case in C++. Otherwise I had no reason to generally assume the compiler
would elide copies.
I don’t understand what caused the author to assume that a compiler would elide the copy when passing a value argument to a function. That seems like an unfounded assumption to me and I don’t think there is anything sad about it not being true.
To avoid the copy in all cases the “consume” function should probably accept a reference argument. That would be idiomatic C++.
- krona 6y agoThis. The compiler is doing the least surprising thing here - I don't understand the author's confusion.
- PartiallyTyped 6y agoBy accepting a reference argument, you introduce pointer deref. Wouldn't it be better to use Widget && temp = complicated_long_function(...); consume(temp); Am i missing something?
- AzN1337c0d3r 6y agoYour proposed example code does exactly what GP said, pass as a reference (in your case, an rvalue reference).
- CyberRabbi 6y agoNot quite, I suggested changing the signature of “consume” to accept a reference. His example doesn’t do anything to invoke copy elision, since his named rvalue reference will be function cast to a normal reference and then copy-constructed into the stack value passed to “consume”.
- AzN1337c0d3r 6y agohttps://gcc.godbolt.org/z/qd5qnhPT6 https://gcc.godbolt.org/z/qd5qnhPT6 How does any copy-construction happen here?
- deleted 6y ago[deleted]
- CyberRabbi 6y agoThat won’t work. Copy elisions only happen when they are copy constructed from prvalues, not simply an rvalue. The pointer deref is unavoidable if you pass a large enough object by value, which is what’s happening here. On x86_64, generally values larger than 16 bytes are passed by reference transparently.
- PartiallyTyped 6y agoI see, thanks!