如何防止客户端将nullptr传递给构造函数?

iFr*_*cht 4 c++ constructor unique-ptr c++11

使用期望a的构造函数std::unique_ptr,如何防止客户端nullptr有效传递?

class Foo{
    Foo(std::unique_ptr<Bar> bar) :
        myBar(std::move(bar))
    {}
}
Run Code Online (Sandbox Code Playgroud)

我可以使用nullptr_t参数重载构造函数,然后将其设置为已删除以nullptr在编译时检测某些s吗?

Foo(nullptr_t) = delete;
Run Code Online (Sandbox Code Playgroud)

nullptr当我已经在初始化列表中移动它时,我可以在构造函数的主体中安全地检查吗?(有事告诉我,我不能)

Foo(std::unique_ptr<Bar>) :
    myBar(std::move(bar))
{ 
    if(!bar)
        throw invalid_argument();
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*ian 5

我会结合两种方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

删除的构造函数将阻止某人执行Foo{nullptr}但不会阻止Foo{std::unique_ptr<Bar>{}},因此您还需要在构造函数体内进行检查.

但是,您无法检查参数barmove,该检查将始终失败.检查myBar您移入的数据成员()unique_ptr.