Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared_ptr entirely on stack

Assuming I know the stack frame will outlive all the copies of the shared_ptr, is there any way to create a shared_ptr to a stack object such that the reference counter is also on the stack so that there's no dynamic allocation at any point?

e.g.

SomeObject anObject;
std::shared_ptr::ref_counter refCounter; // Does this exist?

std::shared_ptr<SomeObject>(&anObject, &refCounter, [](SomeObject* obj){
    obj->DoSomething();
});

The goal here being to use shared_ptr for its reference counting rather than as a smart pointer.

EDIT: I'm gonna add some more explanation to make the reasons for doing this more clear.

I'm trying to create a token that calls a function when it and all its copies are destroyed for a threading library I'm writing. Each token is essentially just a wrapper for a smart pointer to a persistent object that holds the function and calls it in its destructor. Copying the token copies the wrapper (and thus the smart pointer), but not the persistent object.

Given that these tokens may be passed to many different threads the persistent object usually needs to be on the heap, but some of the time I can actually guarantee that a particular stack frame will outlive all the copies of any tokens it creates. In those situations the persistent part of the token can be created on the stack, forgoing any expensive heap allocation.

So in some situations the smart pointer does need to actually own the object it's pointing to, but in others it doesn't.

like image 611
nzerbzer Avatar asked Oct 27 '25 04:10

nzerbzer


1 Answers

There is no way to manage a stack allocated object with a shared pointer.

However, there should not be any need for it either. In place of the shared pointer, you can use a bare pointer or perhaps a reference. Since you know that the referenced object will outlive all users, it is safe.


I'm trying to create a token that calls a function when it and all its copies are destroyed

For that, you don't want to use a shared pointer. You should just implement your own reference counter.

like image 193
eerorika Avatar answered Oct 29 '25 17:10

eerorika