【发布时间】:2012-06-03 23:19:45
【问题描述】:
我有一个名为 Foo 的结构,其中包含一个 unique_ptr
struct Foo {
std::unique_ptr<Bar> pointer;
};
现在我正在尝试将Foo 的实例存储在unordered_map 中
std::unordered_map<int,Foo> myMap;
从技术上讲,这应该是可能的,因为地图不需要复制构造函数,只需要移动构造函数。
但是,我无法在我的地图中插入元素:
myMap.insert(std::make_pair(3, Foo()));
这一行会在 Visual C++ 2010 中产生以下错误(由我粗略翻译,因为我的编译器不是英文的):
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&)'
因此,由于未知原因,编译器尝试为Foo 生成复制构造函数而不是移动构造函数,但失败了。
我尝试将std::make_pair 替换为std::pair<int,something>,但找不到任何有效的something。
编辑:这行得通
struct Foo {
Foo() {}
Foo(Foo&& other) : pointer(std::move(other.pointer)) {}
std::unique_ptr<Bar> pointer;
};
但我的真实结构包含很多成员,我不想将它们全部写在移动构造函数中。
【问题讨论】:
标签: c++ visual-studio-2010 constructor move unordered-map