Shared_ptr completely on the stack

Assuming I know that the stack frame will outlive all copies shared_ptr

, is there a way to create an object shared_ptr

for the stack object so that the reference count is also on the stack so that there is no dynamic allocation at any point?

eg.

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

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

      

The intent here is to be used shared_ptr

for reference counting, not as a smart pointer.

EDIT: I'm going to add some more explanations to make the reasons for this clearer.

I am trying to create a token that calls a function when it and all copies of it are destroyed for a thread library I am writing. Each token is essentially just a wrapper for a smart pointer to a constant object that contains that function and calls it in its destructor. Copying the token copies the wrapper (and therefore the smart pointer), but not the persistent object.

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

Thus, in some situations, a smart pointer should actually own the object it points to, and in others it should not.

+3


source to share


2 answers


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

However, this should not be necessary either. Instead of a generic pointer, you can use a null pointer, or possibly a link. Since you know the referenced object will outlive all users, it is safe.




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

You don't want to use a shared pointer for this. You should just implement your own reference count.

+3


source


you can do it, but it won't be a good choice *.


SomeObject anObject;
std::shared_ptr<SomeObject>(&anObject, [](auto x){}});

      

coliru example




* this doesn't use most of the functionality shared_ptr

and is a waste, and counter can be written in many other ways, including implementing your own counting class.


I really see no reason to prevent dynamic allocation. Even if you can't use the heap, dynamic allocation can happen entirely on the stack.

0


source







All Articles