I would like to know whether the following code will result in an increase in the reference count for each shared pointer, or whether the optimizer will be clever enough to recognize that we are not in fact copying the pointer, just dereferencing it.
std::map<int, std::shared_ptr<foo>> map;
...
for (auto kv : map)
kv.second->func();
kv
is a std::pair<int, std::shared_ptr<foo>>
Since the range-based for-loop will return a stack-allocated std::pair
, which in turn stores a copy of the std::shared_ptr
, I believe that the reference count will be increased at this point.
However, it is plain to see that this copy is just temporary, and the intention here is not to copy ownership, but just dereference the currently owned copy.
But since the creation of the pair causes a a side-effect, an increase in the reference count, does this mean the optimizer will not be able to optimize this copy out, or have the compiler/optimizer writers recognized this use-case and been able to optimize out the copy?