Reputation: 531
I have read that the C++ compiler does the optimization for you (,or at least should) and that the programmer shouldn't worry too much about it.
But how does this compare to pointers? It seems that every time you make a function you have to decide whether to use pointers or not. What's the reason behind this? Shouldn't the compiler do this for you as far as possible?
And isn't there a keyword which you can use in the method signature that states that the objects given as parameter won't be mutated so that the compiler could optimize stuff?
And why is(n't) there one?
Upvotes: 0
Views: 762
Reputation: 30489
Using object as argument, a compiler may or may not do the copy ellision depending on many factors. If in doubt compiler can make a safe assumption that function may want to change the argument and may avoid copy elision optimization.
Instead if you use (const) reference or a pointer, it provides stronger guarantee to the compiler that either object won't change or changes done locally in the function are required in the caller also.
In general one should avoid avoid micro optimizations unless proven bottleneck using some profiling and concentrate on readability of code for better maintenance and architectural changes which can give higher optimization and can not be suggested/performed by tools.
Upvotes: 1