mardi 25 août 2015

Trying to return a `std::unique_ptr` constructed with `NULL`

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 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

Thanks, erip

EDIT

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!"

Aucun commentaire:

Enregistrer un commentaire