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);
}
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.
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