Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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<int,std::default_delete attempting to reference a deleted function ptrTest c:\ptrtest\main.cpp 7
#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 doesn'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), this code throws the same error. Now I know that it's not valid (I declared the first unique_ptr as an 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);
}
like image 661
friartuck Avatar asked Mar 11 '23 00:03

friartuck


1 Answers

Yes.

The only potentially viable candidate for the call during lookup is the copy constructor, as the compiler tries to perform a copy initialisation… which it then finds is impossible because said constructor is deleted. It's a multi-step process.

You could call this a C++ quirk, maybe, in that the diagnostic is a bit of an abstraction leak. But it does make sense from a technical standpoint.

like image 177
Lightness Races in Orbit Avatar answered Apr 06 '23 09:04

Lightness Races in Orbit