Visual C++ 2010 : unordered_map and move constructor

纵然是瞬间 提交于 2019-12-13 05:56:52

问题


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.


回答1:


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.




回答2:


I don't think Visual C++ 2010 supports move constructors.




回答3:


The C++11 move constructor's biggest benefit is that it can coexist with a copy constructor. If you don't have and don't want a copy constructer and your C++ standard library implementation is lacking emplace support, you can simply implement the move in your copy constructor, either by explicitly doing the move or by reimplementing the logic.

The only drawback to this is that you won't get any of the compile time errors when you attempt to copy instead of move your structure, which will result in possibly subtle issues that will (again possibly) take you a while to find..



来源:https://stackoverflow.com/questions/10870359/visual-c-2010-unordered-map-and-move-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!