Reputation: 3235
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.
Upvotes: 3
Views: 3158
Reputation: 32847
The @Berto99's answer has mentioned the problem(i.e. UB) of calling the std::vector::back
for a empty std::vector
.
In addition, like @RemyLebeau mentioned, if you use the std::make_unique
, it will always return the std::unique_ptr
of an instance of type T
(i.e. BaseClass
).
I would like to add something to your actual question. If you want to check anything regarding the last insertion, you could use std::vector::emplace_back
, which returns (since C++17) the references to the inserted element.
std::vector<std::unique_ptr<BaseClass>> vec;
auto& lastEntry = vec.emplace_back(std::make_unique<BaseClass>());
if (lastEntry) // pointer check
{
// do something with the last entry!
}
As a plus over std::vector::push_back
, your std::unique_ptr<BaseClass>
will be constructed in-place.
Upvotes: 2
Reputation: 12939
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
Upvotes: 4