Home > Back-end >  shared_ptr use_count event once a certain value is reached
shared_ptr use_count event once a certain value is reached

Time:12-09

For better performance in memory management (new resp. malloc takes very much time in my application) I want to reuse objects wrapped by shared_ptr.

I know that the objects have to be deleted as soon as use_count() reaches a certain value. Currently when use_count() equals that value I remove the objects from their containers that they are deleted and create new objects when needed.

Is there a way to get an event (function, lambda expression, whatever) as soon as use_count() reaches a certain value? If there would be a way, I could write the objects in a list to be reused instead of deletion.

edit: My idea is as follows - written down quickly.

class MyClass {
public:
  MyClass() {};
  virtual ~MyClass() {}
  atomic<shared_ptr<MyClass>> next;
};

// allocate memory quickly in one block
vector<shared_ptr<MyClass>> memory;
memory.reserve(SIZE);
for(unsigned int i = 0; i < SIZE;   i) memory.emplace_back(make_shared<MyClass>());

atomic<shared_ptr<MyClass>> pool = memory[0];
for(unsigned int i = 0; i < SIZE - 1;   i) memory[i]->next = memory[i 1];

// object "creation"
shared_ptr<MyClass> create() {
  // here everything should be atomically done
  shared_ptr<MyClass> c = pool;
  pool = c->next;
  return c;
}

// object ready for reuse
void deletion_if_use_count_is_1(shared_ptr<MyClass> d) {
  // here everything should be atomically done
  d->next = pool;
  pool = d;
}

Perhaps there's a better way to achieve this? But as you can see, use_count() will never be 0, but I want to reuse the objects; the shared_ptr don't need to be touched.

CodePudding user response:

You can use a custom deleter for your shared_ptr that actually does not delete the underlying object but inserts its pointer into a list of reusable objects.

You can't specify deleters with make_shared so you will have to write your own, eg:

std::shared_ptr<ExpensiveType> make_shared_ExpensiveType(ExpensiveType* expensiveType)
{
    return std::shared_ptr<ExpensiveType>(expensiveType, deleterFunc);
}
  • Related