Search code examples
c++factorysmart-pointerstemporary

Factories: how to pass temporary smart pointers to functions. C++


I have a class Foo

class Foo;

a factory returning a pointer to it:

std::unique_ptr<Foo> createFoo(); 

and, since I have been told by Herb that a plain function with no special claim on the lifetime of Foo should take plain naked pointers:

void plainf(Foo* f);

How is my client supposed to correctly do this?

plainF(createFoo());

He would not be happy if he had to write:

auto someName = createFoo();
plainF(someName.get()); 

Solution

  • You can use the get member function which returns a raw pointer to the owned object.

    plainF(createFoo().get());
    

    The temporary created by createFoo() will not go out of scope until plainF has finished. So long as plainF doesn't pass the pointer up out of scope this is completely safe.