lundi 30 janvier 2017

Making a const unique_ptr then trying to std::move from it gives the same error as if you were trying to access the copy constructor

I noticed the error when we try to copy a unique_ptr (e.g. assign one unique pointer to another) is

Error C2280 'std::unique_ptr

#include <memory>

int main()
{
    std::unique_ptr<int> a = std::make_unique<int>(2);
    std::unique_ptr<int> b = a;
}

That's fine, as unique_ptr don't have a copy constructor defined. You don't copy from unique pointers to move (transfer ownership) of the pointer between them.

Interestingly (OK maybe not), but this code throws the same error. Now I know that it's not valid (I declared the first unique_ptr as a immutable object), but the error message implies it is trying to call the copy constructor. Is that correct?

#include <memory>

int main()
{
    const std::unique_ptr<int> a = std::make_unique<int>(2);
    std::unique_ptr<int> b = std::move(a);
}

Aucun commentaire:

Enregistrer un commentaire