Consider some source of data, that holds a shared_ptr
(e.g. a struct member). If you have a guarantee that it is not a temporary value, but will be valid through the current scope and you want have an alias to that pointer: what is more performant, copying the shared_ptr
or having a (possibly const) reference to the original?
Example:
struct S {
shared_ptr<T> ptr;
};
void fun(S s) {
shared_ptr<T> alias1 = s.ptr;
shared_ptr<T> const& alias2 = s.ptr;
/* do something with the alias */
}
Edit: Motivation. This might be necessary, when e.g. 1) getting s.ptr
involves traversing a chain of function calls or derefs or 2) wanting to improve readability.
Tradeoff. Copying the pointer feels more "right" in the sense that it mimics what you would do with a raw pointer, but it requires the refcount mechanism to do its thing (on construction and destruction). On the other hand, having a reference that you potentially use often, incurs additional dereferencing which is in turn expensive (the dereferencing is on top of anything that you would do with the held T
object).
Is there a common rule-of-thumb what is more performant?