在C ++ 11中初始化列表是否合法? [英] Is initializer list like this legal in C++11?

查看:205
本文介绍了在C ++ 11中初始化列表是否合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了C ++的第5版,它说的是最新的标准支持列表初始化。

I read the C++ primer 5th edition, which says that newest standard support list initializer.

我的测试代码如下:

#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:

Then I use 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(),

我选中了 C ++支持Clang的状态,并且看起来它应该已经支持在Clang 3.1中的初始化器列表但是为什么我的代码不工作有人有想法

I checked the C++ support status of Clang, and it looks that it should already support Initializer lists in Clang 3.1. But why does my codes doesn't work. Does anyone have ideas about this?

推荐答案

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

The code is legal, the problem is with your compiler+stdlib setup.

Apple的Xcode附带了GNU C ++标准库libstdc ++的古代版本4.2.1(请参见 http:/ /stackoverflow.com/a/14150421/981959 了解详情),该版本早于C ++ 11多年,因此它的 std :: vector 没有初始化列表构造函数。

Apple's Xcode ships with the ancient version 4.2.1 of the GNU C++ standard library, libstdc++ (see http://stackoverflow.com/a/14150421/981959 for details) and that version pre-dates C++11 by many years so its std::vector doesn't have an initializer-list constructor.

要使用C ++ 11的功能,你需要安装和使用一个更新的libstdc ++,或告诉clang使用苹果自己的libc ++库,您可以使用 -stdlib = libc ++ 选项。

To use C++11 features you either need to install and use a newer libstdc++, or tell clang to use Apple's own libc++ library, which you do with the -stdlib=libc++ option.

这篇关于在C ++ 11中初始化列表是否合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆