std::for_each编译错误,使用g++,而不是VS2012

std::for_each compile error with g++, not VS2012

本文关键字:g++ VS2012 使用 错误 for each 编译 std      更新时间:2023-10-16

我有以下代码(尽可能简化):

#include <vector>
#include <algorithm>
using std::vector;
enum class Foo {
BAR, BAZ
};
void print_to_file(const vector<const vector<Foo> >& sequences) {
std::for_each(sequences.begin(), sequences.end(), [](const vector<Foo>& sequence) {
});
}
int main(int argc, char **argv) {
return EXIT_SUCCESS;
}

当用g++ (SUSE Linux) 4.7.1 20120723 [gcc-4_7-branch revision 189773]作为g++ --std=c++11 test.cpp编译时,我得到以下错误消息:

In file included from /usr/include/c++/4.7/x86_64-suse-linux/bits/c++allocator.h:34:0,
from /usr/include/c++/4.7/bits/allocator.h:48,
from /usr/include/c++/4.7/vector:62,
from test.cpp:1:
/usr/include/c++/4.7/ext/new_allocator.h: In instantiation of ‘struct __gnu_cxx::new_allocator<const std::vector<Foo> >’:
/usr/include/c++/4.7/bits/allocator.h:89:11:   required from ‘class std::allocator<const std::vector<Foo> >’
/usr/include/c++/4.7/bits/alloc_traits.h:89:43:   required from ‘struct std::allocator_traits<std::allocator<const std::vector<Foo> > >’
/usr/include/c++/4.7/ext/alloc_traits.h:109:10:   required from ‘struct __gnu_cxx::__alloc_traits<std::allocator<const std::vector<Foo> > >’
/usr/include/c++/4.7/bits/stl_vector.h:76:28:   required from ‘struct std::_Vector_base<const std::vector<Foo>, std::allocator<const std::vector<Foo> > >’
/usr/include/c++/4.7/bits/stl_vector.h:208:11:   required from ‘class std::vector<const std::vector<Foo> >’
test.cpp:11:25:   required from here
/usr/include/c++/4.7/ext/new_allocator.h:83:7: error: ‘const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const std::vector<Foo>; __gnu_cxx::new_allocator<_Tp>::const_pointer = const std::vector<Foo>*; __gnu_cxx::new_allocator<_Tp>::const_reference = const std::vector<Foo>&]’ cannot be overloaded
/usr/include/c++/4.7/ext/new_allocator.h:79:7: error: with ‘_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const std::vector<Foo>; __gnu_cxx::new_allocator<_Tp>::pointer = const std::vector<Foo>*; __gnu_cxx::new_allocator<_Tp>::reference = const std::vector<Foo>&]’

同样的代码在VS2012中编译得很好,但在g++下失败得很厉害,我根本不知道如何解释错误消息。

我很惊讶你在其他地方没有遇到问题,因为这个vector<const vector<Foo> >不是一种可能的数据类型。

std::vector的value_type至少必须是可复制的(C++03)或可移动的(C++11)。如果它是常量,则不能分配或移动它。

用于标准容器的分配器要求不允许容器持有const对象。C++11 17.6.3.5"分配器需求"概述了标准分配器的需求,使用了一组以表27开头的表。在表27中,第一个定义是"描述性变量"TUC,它们被定义为"任何非常量、非引用对象类型"。用于分配器类定义的描述性变量XY为:

X-类型为T的分配器类

Y-类型U的相应分配器类

总之,标准分配器是根据非常量类型的参数化定义的。

早在2004年,就有一个旧的GCC/libstdc++错误(被解析为无效)(C++2003对在容器中存储常量对象也有类似的限制,但它更容易显示,因为2003标准更直接地规定,存储在容器中的对象类型必须是"可分配的")。

  • http://gcc.gnu.org/bugzilla/show_bug.cgi?id=16875