简体   繁体   English

如果我指定`shared_ptr,会怎样? <T> &`另一个参考

[英]What happens if I assign `shared_ptr<T>&` to another reference of it

I have implemented Chain of Responsibility design pattern and each element in a chain is a shared_ptr . 我已经实现了责任链设计模式,并且链中的每个元素都是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 . 在这种情况下,我想有first作为链的开始和last和链的一端能够添加使用新链ITMS 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: 在下面的函数中, link是作为局部变量创建的当前链元素,以及我使用以下函数添加到链中的元素:

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. 因此,引用是对对象的引用,它们可能仍会增加使用次数。

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, eg 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. 在您的示例中,如果要修改指向的对象,则应按值传递,也可以按const引用传递。 Thus the former guarantees the lifetime of the object and the second guarantees the lifetime of the referenced shared_ptr. 因此,前者保证对象的生存期,而第二个保证所引用的shared_ptr的生存期。

Nope, it does not increases the use_count. 不,它不会增加use_count。 As @BlueTrin suggested look at why you should not or only when you should pass shared_ptr by reference. 正如@BlueTrin建议的那样,请查看为什么不应该或者仅当您应该通过引用传递shared_ptr时。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM