我有一个很大的数据集,基本上是这样加载的:
for(int i=0;i<count; i++){
auto ptr = std::make_shared<Object>(Object());
//do stuff with ptr
}
这对于性能来说并不是很好,因为内存分配是零散的。 我想做的是这样的:
std::shared_ptr<Object[]> allObjects; //this is stored elsewhere until the program ends
allObjects.reset(new Object[count]);
for(int i=0;i<count; i++){
auto ptr = std::weak_ptr<Object>(&allObjects[i]);
//do stuff with ptr
}
不幸的是这不能编译。我可以这样尝试:
auto ptr = std::shared_ptr<Object>(&allObjects[i]);
这在程序运行时效果很好,但是当然,当 ptr 的所有副本都被销毁时,就要付出惨重的代价。所以我希望 ptr 成为 std::weak_ptr。主数组 std::shared_ptr 将被存储,直到所有weak_ptr被销毁。那么我可以为数组类型 std::shared_ptr 的索引成员创建一个 std::weak_ptr 吗?我只是缺少一些语法吗?我需要不同的容器类型吗?或者我错过了该方法的根本错误?
为此,您可以使用
std::shared_ptr
的别名构造函数:
auto ptr = std::shared_ptr<Object>(allObjects, &allObjects[i]);
// and if you wanted a weak_ptr
auto ptr = std::weak_ptr(std::shared_ptr<Object>(allObjects, &allObjects[i]));
这个
ptr
将使用与 allObjects
相同的控制块(因此它将具有相同的 use_count
并同时被销毁,而且最重要的是仅被销毁一次)