Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why const_cast is not allowed for unique_ptr?

I am trying to const_cast unique_ptr and it is giving me error :

  const std::unique_ptr<int> myptr;
  std::unique_ptr<int> myptr1 = std::move(const_cast<std::unique_ptr<int> >(myptr));

So I want to understand why const_cast doesn't work with unique_ptr if it can work with normal pointers ?

like image 874
PapaDiHatti Avatar asked Nov 17 '25 07:11

PapaDiHatti


1 Answers

You can const cast a unique_ptr. What you can't do is move from a const unique_ptr, which is what your code attempts to do. You could do this though:

vec.push_back(std::move(const_cast<std::unique_ptr<int>&>(myptr)));

Of course, this is undefined behavior, since your unique_ptr is actually const. If myptr was instead a const reference to a unique_ptr which was not actually const, then the above would be safe.

In your new code

std::unique_ptr<int> myptr1 = std::move(const_cast<std::unique_ptr<int> >(myptr));

The const cast tries to copy myptr before passing the result to std::move. You need to cast it to a reference in order to not copy it.

std::unique_ptr<int> myptr1 = std::move(const_cast<std::unique_ptr<int>& >(myptr));
//                                                                     ^
like image 91
Benjamin Lindley Avatar answered Nov 19 '25 20:11

Benjamin Lindley