C++11中这样的初始化列表是否合法?

4

我读过C++ Primer第五版,书中提到最新的标准支持列表初始化。

我的测试代码如下:

#include <iostream>
#include <string>
#include <cctype>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::ispunct;
int main(int argc, char *argv[])
{
    vector<int> a1 = {0,1,2};
    vector<int> a2{0,1,2}; // should be equal to a1
    return 0;
}

然后我使用Clang 4.0:

bash-3.2$ c++ --version
Apple clang version 4.0 (tags/Apple/clang-421.0.60) (based on LLVM 3.1svn)
Target: x86_64-apple-darwin12.2.0
Thread model: posix

然后按照以下方式进行编译:

c++ -std=c++11 -Wall    playground.cc   -o playground

然而,它报错如下:
playground.cc:13:17: error: no matching constructor for initialization of
      'vector<int>'
    vector<int> a1 = {0,1,2};
                ^    ~~~~~~~

 /usr/include/c++/4.2.1/bits/stl_vector.h:255:9: note: candidate constructor
  [with _InputIterator = int] not viable: no known conversion from 'int'
  to 'const allocator_type' (aka 'const std::allocator<int>') for 3rd
  argument;
    vector(_InputIterator __first, _InputIterator __last,
    ^
/usr/include/c++/4.2.1/bits/stl_vector.h:213:7: note: candidate constructor
  not viable: no known conversion from 'int' to 'const allocator_type'
  (aka 'const std::allocator<int>') for 3rd argument;
  vector(size_type __n, const value_type& __value = value_type(),

我查看了Clang的C++支持状态,看起来它应该已经在Clang 3.1中支持初始化列表。但是为什么我的代码不能正常工作呢?有没有人有关于这个问题的想法?


1
我猜这只是库没有更新以具有初始化列表构造函数。 - chris
@chris 谢谢!有没有简单的方法更新库? - Hanfei Sun
我无法确定。不幸的是,我一直在Windows上完成所有工作,没有使用Clang。 - chris
同样https://dev59.com/n2ox5IYBdhLWcg3wOx1i?rq=1和那里的被接受的答案 - Jonathan Wakely
http://liveworkspace.org/code/UedRt$7 您的代码在这里可以运行。可能是库的问题。 - Arpit
1个回答

6
代码是合法的,问题出在你的编译器和标准库设置上。
苹果的Xcode附带了古老的GNU C++标准库libstdc++ 4.2.1版本(详见https://dev59.com/JWzXa4cB1Zd3GeqPXcn0#14150421),该版本早于C++11多年,因此其std::vector没有初始化列表构造函数。
要使用C++11功能,您需要安装并使用更新的libstdc++,或告诉clang使用苹果自己的libc++库,这可以通过使用选项-stdlib=libc++来实现。

OP从未说过他在使用Xcode,事实上这甚至没有在帖子中暗示。虽然这可能是问题所在,但结果无论如何都不是来自Xcode。 - Richard J. Ross III
5
我没有说他在使用Xcode,我只是说Xcode附带了GCC 4.2.1,这是事实。错误中的头文件包含路径显示这些头文件来自于GCC 4.2.1,它是早于C++11标准的。如果不是因为这个版本是随Xcode一起发布的版本,那么还有什么其他原因会导致有人安装GCC 4.2.1呢? - Jonathan Wakely
谢谢您的帮助!我现在明白原因了。在添加-stdlib=libc++选项后,它可以工作。 - Hanfei Sun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接