0

I have implemented Chain of Responsibility design pattern and each element in a chain is a shared_ptr. In this case I want to have first as a start of the chain and last and an end of the chain to be able to add new chain itms using last. In the function below link is the current chain element created as a local variable and what I add to the chain using the function below:

void addLink(std::shared_ptr<ILink>& first, std::shared_ptr<ILink>& last, std::shared_ptr<ILink>& link)
{
    if (first == nullptr)
    {
        first = link;
        last = first;
    }
    else
    {
        last->setSuccessor(link);
        last = link;
    }
}

Is it a good practice to use all references and will it increase the ref count?

EDIT:

This methods is being called like this:

    std::shared_ptr<T> first;
    std::shared_ptr<T> last = first;
    const std::shared_ptr<T> link = std::make_shared<T>(some_arguments_here);

So the references are references to objects and they may increase the use count, still.

Narek
  • 38,779
  • 79
  • 233
  • 389
  • 1
    Possible duplicate of [Should I pass a shared\_ptr by reference?](http://stackoverflow.com/questions/8385457/should-i-pass-a-shared-ptr-by-reference) – BlueTrin Dec 03 '15 at 09:43
  • Does it work? What are the alternatives? – Kerrek SB Dec 03 '15 at 09:46
  • You don't make a copy of the `std::shared_ptr` so there is no way that can increase the ref-count on itself. Therefore It doesn't strike me as particularly good practice. You pass a `shared_ptr` by value to guarantee the validity of the pointed to object. That's the whole point. – StoryTeller - Unslander Monica Dec 03 '15 at 09:57

2 Answers2

1

If there is no copying happening there is no issue with the reference.Thus it does not increment. And it should not as references do not get the same semantics as objects, e.g. the destructor is not called when you go out of scope ( how to decrement the counter then ? ) .

In your example you should either pass by value if you intend to modify the pointed object or by const reference. Thus the former guarantees the lifetime of the object and the second guarantees the lifetime of the referenced shared_ptr.

g24l
  • 3,055
  • 15
  • 28
0

Nope, it does not increases the use_count. As @BlueTrin suggested look at why you should not or only when you should pass shared_ptr by reference.

Please see output of below code.

#include <iostream>
#include <memory>

using namespace std;

typedef shared_ptr<int> APtr;
int main()
{
        APtr aptr1(new int);
        cout << "Use Count :" << aptr1.use_count() << endl;
        APtr aptr2 = aptr1;
        cout << "Use Count :" << aptr1.use_count() << endl;
        APtr& aptr3 = aptr1;
        cout << "Use Count :" << aptr1.use_count() << endl;
}

Output

Use Count :1
Use Count :2
Use Count :2
rahul.deshmukhpatil
  • 977
  • 1
  • 16
  • 31