保持shared_ptruse_count()为1
我找不到与此类似的问题,如果我错过了,请指导我!我正在试验智能指针,并来到这个场景,我想将use_count() shared_ptr 对象中返回的值保持为 1(练习优化代码)。这是我正在使用的一个片段:
#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()
这个程序的输出是
2
2
因为两个共享ptr的use_count都是2。谁能告诉我为什么我不能把它们保持在1?我怀疑在传递testFunc整个向量时“传递”向量是创建每个共享 ptr 的副本,但是这让我感到惊讶,因为我是通过引用传递向量。非常感谢任何输入!
回答
问题是临时initializer_list<shared_ptr>保留元素的副本,并且它一直存在到完整表达式(;)。
你能做的不多,一个 initializer_list总是通过副本存储其元素。
作为解决方法,您可以预先构建向量:
std::vector<std::shared_ptr<int>> list{std::move(sharedTest), std::move(anotherSharedTest)};
testFunc(list);
应该打印1 1。