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

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

问题描述

我阅读了 C++ 入门第 5 版,其中提到了最新的标准支持列表初始化程序.

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

我的测试代码是这样的:

My test code is like this:

#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

但是,它的抱怨是这样的:

However, it complains like this:

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++支持状态,看来应该已经支持Initializer了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(请参阅 https://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 https://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 使用 Apple 自己的 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天全站免登陆