简体   繁体   English

保持 shared_ptr use_count() 为 1

[英]keeping shared_ptr use_count() at 1

I was unable to find a similar question to this one, please direct me to one if I missed it, I am experimenting with smart pointers, and came to this scenario where I would like to keep the value returned by use_count() in a shared_ptr object to 1 (to practice optimizing code).我找不到与这个类似的问题,如果我错过了,请指导我,我正在尝试智能指针,并遇到了这种情况,我想将use_count()返回的值保留在 shared_ptr object 为 1(练习优化代码)。 Here is a snippet I am working with:这是我正在使用的一个片段:

#include <iostream>
#include <memory>
#include <vector>

// testFunc: displays the use_count of each shared ptr in the list
void testFunc(const std::vector<std::shared_ptr<int>> &list) {
    // reference each shared ptr in the list and display their use_count
    for (auto &elem : list) {
        std::cout << elem.use_count() << std::endl;
    }   
} // testFunc()

int main() {
    // allocate shared ptr instance of an int
    auto sharedTest = std::make_shared<int>(11);

    // allocate another shared ptr instance of another int
    auto anotherSharedTest = std::make_shared<int>(22);

    // use std::move to prevent another copy of the shared ptrs from being created
    testFunc({ std::move(sharedTest), std::move(anotherSharedTest) }); 

    return 0;
} // main()

The output by this program is该程序的 output 是

2
2

since the use_count of both shared ptrs is 2. Can anyone show me why I cannot keep them at 1?因为两个共享ptrs的use_count都是2。谁能告诉我为什么我不能把它们保持在1? I suspect that "passing" the vector to testFunc is creating a copy of each shared ptr when the entire vector is being passed, however this surprises me since I am passing the vector by reference.我怀疑当传递整个向量时,将向量“传递”给testFunc会创建每个共享 ptr 的副本,但这让我感到惊讶,因为我通过引用传递向量。 Any input is greatly appreciated!非常感谢任何输入!

The problem is the temporary initializer_list<shared_ptr> keeps a copy of the elements, and it lives until the end of the full-expression (the ; ).问题是临时initializer_list<shared_ptr>保留元素的副本,并且它一直存在到完整表达式( ; )的末尾。

There isn't much you can do, an initializer_list always stores its elements by copy.您无能为力, initializer_list总是通过副本存储其元素。

As a workaround, you can construct the vector beforehand:作为一种解决方法,您可以预先构造向量:

std::vector<std::shared_ptr<int>> list{std::move(sharedTest), std::move(anotherSharedTest)};
testFunc(list);

Should print 1 1 .应该打印1 1

According to this answer , std::initializer_list only allows const access to its elements.根据这个答案, std::initializer_list 只允许 const 访问其元素。 This means that the std::vector constructor needs to copy all elements from the list (because move is non-const).这意味着 std::vector 构造函数需要从列表中复制所有元素(因为 move 是非常量的)。

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

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