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.
Nullability - a scoped_ptr or unique_ptr can be null, a value object can never be. Polymorphism - a value object is always exactly its static type, but you can substitute in different derived types for a unique_ptr. The previously-held object is automatically destroyed when you do this.
A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.
unique_ptr::getReturns a pointer to the managed object or nullptr if no object is owned.
I think that what you want is an empty unique_ptr
:
return std::unique_ptr<Foo>();
It seems that you are looking for a pointer that points to no object (and is false
when converted to bool
).
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