I have a structure named Foo which contains a unique_ptr
struct Foo {
std::unique_ptr<Bar> pointer;
};
Now I’m trying to store instances of Foo in an unordered_map
std::unordered_map<int,Foo> myMap;
Technically this should be possible, since maps do not require a copy constructor, only a move constructor.
However, I can’t insert an element in my map:
myMap.insert(std::make_pair(3, Foo()));
This line will generate the following error in Visual C++ 2010 (roughly translated by me, since my compiler is not in english):
error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : unable to access private member declared in 'std::unique_ptr<_Ty>'
with
[
_Ty=Foo
]
c:\Softwares\Visual Studio 10.0\VC\include\memory(2347) : see declaration of 'std::unique_ptr<_Ty>::unique_ptr'
with
[
_Ty=Foo
]
This diagnostic happened in the compiler-generated function 'Foo::Foo(const Foo&)'
So for an unknown reason, the compiler tries to generate a copy constructor for Foo instead of a move constructor, and fails.
I tried to replace std::make_pair with std::pair<int,something>, but can’t find any something which works.
EDIT : this works
struct Foo {
Foo() {}
Foo(Foo&& other) : pointer(std::move(other.pointer)) {}
std::unique_ptr<Bar> pointer;
};
But my real structure contains a lot of members, and I don’t want to write all of them in the move constructor.
MSVC10 (in Visual Studio 2010) doesn’t implement implicit move constructors yet (not surprising since implicit move constructors got into the standard quite late – there was a lot of discussion about it). They won’t be in MSVC11 (in the not-yet-released Visual Studio 2012) either.
I would suggest using
=default, but that’s not supported yet either.