Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::unique_ptr have an equality operator?

I've been thinking about it recently, and the only argument I can see for having an equality operator for std::unique_ptr is for completeness so all of the smart pointers in the standard template library have it. But unless you've done something wrong, I can't see any example where it might return true.

It's obviously possible to do something like:

int* a = new int(1);
std::unique_ptr<int> u_a1(a);
std::unique_ptr<int> u_a2(a);

if(u_a1 == u_a2)
{
    std::cout << "I'm double deleting soon" << std::endl;
}

But doesn't the inclusion of the operator just allow for people to make these kind of mistakes without the compiler throwing an error? Wouldn't it make more sense to remove it, or am I missing something?

like image 370
FlamFace Avatar asked Apr 02 '20 21:04

FlamFace


People also ask

What is the use of std :: unique_ptr?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

How does C++ unique_ptr work?

A unique_ptr object wraps around a raw pointer and its responsible for its lifetime. When this object is destructed then in its destructor it deletes the associated raw pointer. unique_ptr has its -> and * operator overloaded, so it can be used similar to normal pointer.

Why would you choose Shared_ptr instead 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.

How is unique_ptr implemented in C++?

I have following C++ code snippet, which implements a unique pointer logic: template<typename T> class unique_ptr { private: T* _ptr; public: unique_ptr(T& t) { _ptr = &t; } unique_ptr(unique_ptr<T>&& uptr) { _ptr = std::move(uptr. _ptr); uptr.


1 Answers

Equality actually can return true. The simplest case is two empty pointers:

std::unique_ptr u_a1;
std::unique_ptr u_a2;

if (u_a1 == u_a2) // ...

The operators also allow comparing unique_ptr<T, D> objects with different types, so you might have two different deleter types which will do different things to the same pointer on cleanup. Or even some deleter other than the default deleter which intentionally can do the same thing more than once (a counter?).

The presence of the operators might also make the type valid in some templates which would happen to want to compare objects of its dependent types.

like image 54
aschepler Avatar answered Sep 25 '22 19:09

aschepler