保持 shared_ptr use_count() 为 1
keeping shared_ptr use_count() at 1
我找不到与此问题类似的问题,如果我错过了,请告诉我一个问题!
我正在试验智能指针,并遇到了这种情况,我想将 shared_ptr 对象中 use_count()
返回的值保持为 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
因为两个共享指针的 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
.
根据 this answer,std::initializer_list 只允许常量访问它的元素。这意味着 std::vector 构造函数需要从列表中复制所有元素(因为 move 是非常量)。
我找不到与此问题类似的问题,如果我错过了,请告诉我一个问题!
我正在试验智能指针,并遇到了这种情况,我想将 shared_ptr 对象中 use_count()
返回的值保持为 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
因为两个共享指针的 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
.
根据 this answer,std::initializer_list 只允许常量访问它的元素。这意味着 std::vector 构造函数需要从列表中复制所有元素(因为 move 是非常量)。