3

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 ?

4
  • 2
    Naturally, you can't move from a const object: move needs to modify the source, in order to "steal" resources from it. Commented Jul 10, 2016 at 3:11
  • so this means i cannot have vector of const std::unique_ptr right ? Commented Jul 10, 2016 at 3:13
  • 1
    I'm pretty sure you indeed cannot. vector's elements must be either copyable or movable, and const unique_ptr is neither. Commented Jul 10, 2016 at 3:14
  • 1
    You cannot have a vector of const int, either. Commented Jul 10, 2016 at 3:15

1 Answer 1

6

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));
//                                                                     ^
Sign up to request clarification or add additional context in comments.

5 Comments

@Kapil: Yes. We can. What you can't do is copy a unique_ptr, which your new code attempts to do.
no even this std::unique_ptr<int> myptr1 = std::move(const_cast<std::unique_ptr<int> >(myptr)); doesn't compile
@Kapil: Because that's still attempting to copy the unique_ptr, in the const_cast itself. You need to cast it to a reference.
@Kapil: i.e. std::unique_ptr<int> myptr1 = std::move(const_cast<std::unique_ptr<int>&>(myptr));
the "in the new code" suggestion is still undefined behaviour (modifying a const object)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.