这样的初始值设定项列表在C++11中合法吗

Is initializer list like this legal in C++11?

本文关键字:C++11 列表      更新时间:2023-10-16

我阅读了C++入门第5版,其中介绍了最新的标准支持列表初始值设定项。

我的测试代码是这样的:

#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中的Initializer列表了。但是为什么我的代码不起作用。有人对此有想法吗?

代码是合法的,问题在于编译器+stdlib设置。

苹果的Xcode附带了GNUC++标准库libstdc++的4.2.1版本(请参阅https://stackoverflow.com/a/14150421/981959详细信息),并且该版本比C++11早了很多年,所以它的std::vector没有初始化器列表构造函数。

要使用C++11功能,您需要安装并使用更新的libstdc++,或者告诉clang使用苹果自己的libc++库,这可以通过-stdlib=libc++选项来实现。