I won't really recommend it, but you can return an object that implicitly converts to a raw pointer. It will own it for a short duration, and delete if no-one grabs it.
struct RelinquishOrDelete {
ExampleClass *_ptr;
operator ExampleClass*() { auto ret = _ptr; _ptr = nullptr; return ret; }
~RelinquishOrDelete() {
if(!_ptr) {
cerr << "returned object wasn't taken by a new owner\n";
delete _ptr;
}
}
};
Using it is simple. It will pack and unpack the pointer in this simple case:
RelinquishOrDelete function()
{
ExampleClass *ptr = new ExampleClass();
ptr->doSomething();
return {ptr};
}
// ...
ExampleClass *ptr2 = function();
But of course, it will likely cause unexpected behavior if used in this perfectly reasonable piece of code:
auto ptr3 = function();
A smart pointer with much stricter ownership semantics is really the best approach.