我有以下简单的示例,我想在一个不可复制的对象集合上调用std::for_each
:
class A {
public:
A() : x(0) {}
A(const A&) = delete;
private:
int x;
};
void func() {
std::vector<A> v(10);
std::map<int, A> m;
// works as expected
std::for_each(begin(v), end(v), [](const A& a) { /* do nothing */ });
// error calling copy constructor
std::for_each(begin(m), end(m), [](const std::pair<int, A>& a) { /* do nothing */ });
}
如果我把所有东西都放进一个std::vector
中,它就像我预期的那样工作,但是使用std::map
时,突然std::for_each
想要调用(已删除的)拷贝构造函数。为什么? 我原本以为只会获得保存在映射中的一对的引用,而不需要进行任何必要的副本。