Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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.

like image 782
erip Avatar asked Aug 25 '15 12:08

erip


People also ask

Can a unique_ptr be null?

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.

Can you copy a unique_ptr?

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.

What does get () do on a unique_ptr?

unique_ptr::getReturns a pointer to the managed object or nullptr if no object is owned.


1 Answers

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

like image 200
Toby Speight Avatar answered Nov 15 '22 05:11

Toby Speight