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]);
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]));