我正在设计一个工厂,它创建不同类型的Foo,我正在尝试使用智能指针.
大多数似乎运行良好,但nullptr由于编译器的限制,我缺少一些重要的功能(即).
我有这个方法:
std::unique_ptr<Foo> createFoo(const std::string &fooType) {
auto it = _registeredFoo.find(fooType); // _registeredFoo is a map
if(it != _registeredFoo.end())
return std::unique_ptr<Foo>(it->second());
return std::unique_ptr<Foo>(NULL);
}
Run Code Online (Sandbox Code Playgroud)
当我测试这个方法时,它永远不会返回一个类似NULL的指针.
这就是我测试方法的方法.
std::unique_ptr<Foo> _foo = FooFactory::getInstance()->createFoo("FOO"); //FOO is registered
if(_foo) {
std::cout << "Hello, World!" << std::endl;
} else {
std::cout << "Goodbye, World!" << std::endl;
}
std::unique_ptr<Foo> _bar = FooFactory::getInstance()->createFoo("BAR"); // BAR is unregisered
if(_bar) {
std::cout << "Hello, World!" << std::endl;
} else {
std::cout << "Goodbye, World!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
我总是看到"你好,世界!"
这让我相信我对std::unique_ptr构造函数的使用有点滥用.任何人都可以给我一个建议,如何在不模仿nullptr自己的情况下解决这个问题?
我正在使用gcc 4.4.6.
我认为你想要的是空的unique_ptr:
return std::unique_ptr<Foo>();
Run Code Online (Sandbox Code Playgroud)
看来你正在寻找一个指向没有对象的指针(并且false在转换为时bool).
小智 6
你可以使用默认的构造函数的std::unique_ptr.
std::unique_ptr<int> a1();
std::unique_ptr<int> a2(nullptr);
Run Code Online (Sandbox Code Playgroud)
a1并且a2是唯一的指针初始化为空(没有任何东西).
您可以使用unique_ptr类提供的运算符bool验证指针的空白:
if (!a1) { // the smart pointer is empty
}
Run Code Online (Sandbox Code Playgroud)
你想要的是什么
return {};
Run Code Online (Sandbox Code Playgroud)
所述{}返回任何(类)的缺省构造的对象类型1,并且可以读出"无".它适用于智能指针,可选,以及大多数一切.
如果你的编译器没有这个
return std::unique_ptr<Foo>();
Run Code Online (Sandbox Code Playgroud)
会做的.无论如何,传递NULL给std::unique_ptrC++ 11是不合法的(构造函数是模糊的).
您没有C++ 11编译器.在代码中使用C++ 11会容易出错.
1正确的措辞很复杂.对于标量(如int),这将零初始化值(实际上,它将值设置为0/ null/0.0/ '\0'etc).