Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an idiomatic way to return a pointer that optionally owns its value

Tags:

c++

stl

I have a function that given a path name, does a look up and returns a pointer to the associated value. Sometimes the value lives in a static cache, sometimes it gets calculated and created on the fly.

So, sometimes the caller takes ownership and needs to delete the object after reading it, and sometimes not. I'm wondering, is there something I can wrap this pointer with so that it will automatically be freed as necessary by the caller?

I was thinking I might be able to use a unique_ptr, but isn't the deleter part of the type, so how could I return the same type that sometimes does and sometimes doesn't actually delete.

like image 321
Scott Langham Avatar asked Nov 07 '25 11:11

Scott Langham


1 Answers

So indeed, one solution could be returning a normal std::shared_ptr for the value created inside the function, and another one with an empty deleter for the value that lives in the map.

Live example of this solution

You can see how both use cases don't require any actions from the calling code and are completely transparent.

like image 64
JBL Avatar answered Nov 10 '25 04:11

JBL