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 ?
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));
// ^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With