Search code examples
c++pointersc++14smart-pointersstdvector

How to check if a std::unique_ptr is null, if it is in a std::vector?


I have a vector<unique_ptr<BaseClass>>, and I am adding new items to it by calling vec.push_back(std::make_unique<DerivedClass>()).

How can I check for nullptr using operator bool()?

I tried to use vec.back() directly, like so:

if((!vec.empty() && vec.back())
{
  // yay!
}
else
{
  //nay!
}

but it always returns with false, regardless of the contents of the pointer.


Solution

  • As you can read from here, if the vector is empty, it's UB. If it's not your case, as you can read from here instead, unique_ptr has a operator bool() which checks whether an object is currently managed by the unique_ptr

    So, with:

    vector.empty();
    

    You can check if the vector has elements, and with:

    vector<unique_ptr<something>> vec;
    vec.push_back(make_unique<something>());
    if(vec.front()){ // example
        // do something
    }
    

    you check whether the first unique_ptr is pointing to an object or not.

    PS: if you always use vec.push_back(std::make_unique<DerivedClass>()), you will never have a unique_ptr that holds a nullptr