为什么映射上的std::for_each调用复制构造函数
Why does std::for_each on a map call the copy constructor?
我有以下简单的例子,其中我想在不可复制的对象集合上调用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
突然想调用(已删除的)复制构造函数。为什么?我会假设我只是得到了一个保存在地图中的对的引用,而没有任何必要的副本。
问题是std::map
的内部值类型为std::pair<const Key, Value>
。标准库容器不需要明确指定,而是允许您从容器类型中提取:
在C++11中执行(与C++98中相同,但必须在for_each
中使用函数对象而不是lambda,还必须使用typedef
而不是using =
):
using value_type = std::map<int, A>::value_type;
std::for_each(begin(m), end(m), [](value_type const& a) { /* do nothing */ });
在C++14中做:
std::for_each(begin(m), end(m), [](auto const& a) { /* do nothing */ });
Clang 3.4、Visual Studio 2013 November CTP和GCC 4.9支持在lambda中使用auto
。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- std::cout.imbue()多重调用
- 只为NOT STATIC类的EACH对象调用一次方法