Trying to return `std :: unique_ptr` built with` NULL`

I am developing a Factory that creates different types of Foo, and I'm trying to use smart pointers.

Most of them seem to work well, but I miss some important functions (namely nullptr) due to 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 pointer NULL.

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 makes me think that my use of the constructor is a std::unique_ptrbit offensive. Can someone give me a recommendation on how to approach this without emulating nullptrmyself ?

I am using gcc 4.4.6.

+4
3

, unique_ptr:

return std::unique_ptr<Foo>();

, , ( false bool).

+6

< <20 > .

std::unique_ptr<int> a1();
std::unique_ptr<int> a2(nullptr);

a1 a2 , ( ).

bool, unique_ptr:

if (!a1) { // the smart pointer is empty
}
+6

return {};

{} () 1 "". , .

return std::unique_ptr<Foo>();

will do it. Passing NULLin is std::unique_ptrnot legal in C ++ 11 anyway (the constructor is ambiguous) .

You do not have a C ++ 11 compiler. Any use of C ++ 11 in your code will be error prone.


1 The correct wording is complicated . For a scalar (e.g. int), this zero initializes the value (which in practice sets the value to 0/ null / 0.0/ '\0', etc.).

+4
source

All Articles