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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With