Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent clients from passing a nullptr to a constructor?

With a constructor that expects a std::unique_ptr, how do you prevent clients from passing a nullptr effectively?

class Foo{
    Foo(std::unique_ptr<Bar> bar) :
        myBar(std::move(bar))
    {}
}

Could I overload the constructor with a nullptr_t argument and then set it as deleted to detect some nullptrs at compile-time?

Foo(nullptr_t) = delete;

Can I safely check for nullptr in the body of the constructor when I already moved it in the initialiser list? (Something tells me I can't)

Foo(std::unique_ptr<Bar>) :
    myBar(std::move(bar))
{ 
    if(!bar)
        throw invalid_argument();
}
like image 340
iFreilicht Avatar asked Jun 06 '14 23:06

iFreilicht


1 Answers

I would combine both approaches:

class Foo{
public:
    Foo(std::unique_ptr<Bar> bar) :
        myBar(std::move(bar))
    {
        if(!myBar)  // check myBar, not bar
            throw invalid_argument();
    }
    Foo(nullptr_t) = delete;
}

The deleted constructor will prevent someone from doing Foo{nullptr} but it won't prevent Foo{std::unique_ptr<Bar>{}}, so you need the check within the constructor body as well.

However, you cannot check the argument bar after moveing it, that check will always fail. Check the data member (myBar) that you moved the unique_ptr into.

like image 173
Praetorian Avatar answered Nov 10 '22 11:11

Praetorian