对于需要 std::unique_ptr
的构造函数,如何防止客户端有效地传递 nullptr
?
class Foo{
Foo(std::unique_ptr<Bar> bar) :
myBar(std::move(bar))
{}
}
我可以用 nullptr_t
参数重载构造函数,然后将其设置为已删除以在编译时检测一些 nullptr
吗?
Foo(nullptr_t) = delete;
当我已经将它移动到初始化列表中时,我可以安全地检查构造函数主体中的 nullptr
吗? (有些东西告诉我我不能)
Foo(std::unique_ptr<Bar>) :
myBar(std::move(bar))
{
if(!bar)
throw invalid_argument();
}
最佳答案
我会结合这两种方法:
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;
}
删除的构造函数将阻止某人做 Foo{nullptr}
但它不会阻止 Foo{std::unique_ptr<Bar>{}}
,因此您还需要在构造函数主体内进行检查。
但是,您无法检查参数 bar
在 move
之后检查它,该支票将 always fail .检查您移动了 myBar
的数据成员 ( unique_ptr
)进入。
关于c++ - 如何防止客户端将 nullptr 传递给构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24091876/