Search code examples
c++memorysmart-pointersreturn-value-optimization

How to return an object pointer with conditional expression?


According to https://www.youtube.com/watch?v=LFv7XwgsdLY&t=1620s 25:40

class Foo should be retured 2 ways:

  • with if
if(condition) 
   return foo1 
else 
    return foo2;
  • with conditional expression
return condition ? food(foo1) : std::move(foo2);

what if Foo is a unique_ptr and I want to check if Foo is not nullptr then return foo and if it is a nullptr return nullptr. Lets forget for now that someone might want to delete that pointer.

which way is the proper one?

Foo* getFoo()
{
    //get because foo is a unique ptr
    return foo ? foo.get() : nullptr;
}
Foo* getFoo()
{
    return foo ? std::move(foo.get()) : nullptr;
}

Solution

  • You don't need any sort of branching. You can just use

    Foo* getFoo()
    {
        return foo.get();
    }
    

    This works because get will return nullptr if foo holds a nullptr.