Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is unique_ptr operator-> not const-overloaded?

std::unique_ptr::operator-> has the signature

pointer operator->() const noexcept;

So operator-> is const but returns a mutable pointer. This allows for code like:

void myConstMemberFunction() const
{
    myUniquePtrMember->nonConstFunction();
}

Why does the standard allow this, and what is the best way to prevent usage as presented above?

like image 527
khuttun Avatar asked Dec 17 '15 11:12

khuttun


People also ask

What happens when Unique_ptr goes out of scope?

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.

When should we use 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.


1 Answers

Think about it like a normal pointer:

int * const i;

is a const pointer to a non-const int. You can change the int, but not the pointer.

int const * i;

is a non-const pointer to a const int. You can change the pointer but not the int.


Now, for unique_ptr, it's a question of whether the const goes inside or outside the <>. So:

std::unique_ptr<int> const u;

is like the first one. You can change the int, but not the pointer.

What you want is:

std::unique_ptr<int const> u;

You can change the pointer, but not the int. Or perhaps even:

std::unique_ptr<int const> const u;

Here you can't change the pointer or the int.


Notice how I always place the const on the right? This is a little uncommon, but is necessary when dealing with pointers. The const always applies to the thing immediately to its left, be that the * (pointer is const), or the int. See http://kuhllib.com/2012/01/17/continental-const-placement/ .

Writing const int, might lead you to thinking int const * is a const-pointer to a non-const int, which is wrong.

like image 194
BoBTFish Avatar answered Oct 11 '22 20:10

BoBTFish