I'm designing a Factory that creates different types of Foo and I'm trying to use smart pointers.
Most seems to be working well, but I am missing some important features (namely nullptr) because of compiler limitations.
I have this method:
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);
}
When I test this method, it never returns a NULL-like pointer.
This is how I test my method.
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;
}
I always see "Hello, World!"
This leads me to believe that my use of std::unique_ptr's constructor is a bit abusive. Can anyone give me a recommendation for how to approach this without emulating nullptr myself?
I'm using gcc 4.4.6.
unique_ptr();help?NULL-like pointer"?unique_ptrto work as it should? You pass ownership of the pointed to memory from the registry to theunique_ptryou return. Theunique_ptrwill calldelete, and your registry will probably calldelete. Same problem if you callcreateFoowith the same argument twice.