3 ms·
> The above code is bad because it makes unnecessary copies. plus doesn’t need its own copies of s and t; it can get by with just references to its caller’s str
by ukoki 5y ago
> The above code is bad because it makes unnecessary copies. plus doesn’t need its own copies of s and t; it can get by with just references to its caller’s strings.
I was under the impression the compiler was smart enough to 'move' rather than 'copy' a value if it can prove it's not reused. And also to infer a 'const' reference if it can prove the reference is not modified.
- nly 5y agoThe compiler isn't allowed to move instead of copy if the code implies a copy. What it can do however is completely elide the copy, and not call the copy constructor. Const isn't really useful to the optimiser in any way, roughly all it does really is effect the overload resolution rules, and how the compiler maps statically initialized data in to your final binary.
- account42 5y ago> Const isn't really useful to the optimiser in any way, roughly all it does really is effect the overload resolution rules, and how the compiler maps statically initialized data in to your final binary. const on pointers and references is not useful at all, but const on variables is useful as it means the value is never allowed to change. For example: const int x = 0; do_something(&x); return x; // Optimizer can assume that x == 0 here even if it knows nothing about do_something See: https://godbolt.org/z/4T8M3eK1x https://godbolt.org/z/4T8M3eK1x