I want to pass an object using a smart-pointer reference to a function. A function can change the value of the object referenced, but cannot change the link itself. There are two obvious ways to handle this.
The first approach for passing the shared_ptr value by value is a link, therefore, by itself should not be passed by reference. The obvious problem with this is copying the link, which involves some overhead for counting.
void foo (shared_ptr<bar> p)
The second approach is to pass shared_ptr via the const link - avoiding copying the shared_ptr instance, but instead implying that accessing the specified object requires two dereferencing layers instead of one.
void foo (const shared_ptr<bar> &p)
In practice, these theoretical overheads are usually trivial and irrelevant. Which tells me that instead of choosing one approach or another for each individual case, I should almost always follow standard conventions. This leads to the question ...
Is there a standard agreement for which of these approaches should I choose? If so, what is the traditional choice?
EDIT . It is probably worth mentioning - one of the reasons for considering the buy-in-constant-reference case is that there is already an agreement that most instances of the class are / by value, and shared_ptr
is a class. Of course, this is not a heavy class (the cost of copying is small), so the reasons for this older agreement may not apply.
Steve314
source share