Is it possible to make std::shared_ptr
not to delete an object, but move it to a list?
#include <memory>
#include <list>
struct QObject { double socialDistance; };
int main()
{
std::list<QObject *> free_objects;
std::list<QObject *> used_objects;
QObject* p_object = new QObject{10};
free_objects.push_back(p_object);
{
std::shared_ptr<QObject> p(p_object);
}
//At this point p_object is moved from free_objects to used_objects,
//so I reuse the object later.
return 0;
}
If yes, is it possible to reuse not only the objects but also the control block to avoid memory reallocation?
Is it possible to make std::shared_ptr not to delete an object, but move it to a list?
You might use custom deleter for that:
std::shared_ptr<QObject> p(p_object, [&](QObject* p){
used_objects.push_back(p);
auto it = std::find(free_objects.begin(), free_objects.end(), p);
if (it != free_objects.end()) free_objects.erase(it);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.