Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr < 0 OR what does less than operator do?

I am dealing with code that has been written not by me. I have this statement:

// p is type of std::unique_ptr<uint8_t[]>
if (p < 0) { /* throw an exception */ }

So what does p < 0 mean in this context?
On the documentation page, I believe my case is 16) y < nullptr, where 0 is nullptr.

But what does it do?

like image 477
Sagid Avatar asked Jan 15 '20 17:01

Sagid


People also ask

What is the use of unique_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

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

What is the advantage of std :: unique_ptr over a plain pointer like t *)?

It means that, if the deleter has no state, the unique_ptr can be no larger than a plain pointer; and moving it no more expensive than copying and nulling a pointer.


Video Answer


2 Answers

unique_ptr < 0 OR what does less than operator do?

It matches the overload (11) on cppreference operator<(const unique_ptr&, nullptr_t);. 0 implicitly converts to std::nullptr_t. As per the documentation, the result is std::less<unique_ptr<T,D>::pointer>()(x.get(), nullptr).

The result is implementation defined, but unconditionally false on probably most systems. Presumably on an exotic system where null doesn't have the binary representation of 0, the result might be true.

I believe my case is 16)

(16) is the same other way around: 0 > unique_ptr. The result is same.

like image 134
eerorika Avatar answered Oct 17 '22 04:10

eerorika


Check that operator < is not overloaded somewhere in your code base. That seems to be the only way how (p < 0) could be true.

Example:

bool operator< (const std::unique_ptr<uint8_t[]>&, int) { return true; }

int main() {
    std::unique_ptr<uint8_t[]> p;
    std::cout << (p < 0) << std::endl;
}

Prints:

1

live demo

Otherwise as others have said, 0 implicitly converts to std::nullptr_t, which would select the bool operator<(const unique_ptr<T, D>& x, nullptr_t) overload which would call std::less(p, 0) which would return false (even on Windows with a -1 pointer value).

like image 20
rustyx Avatar answered Oct 17 '22 03:10

rustyx