【问题标题】:Is initializer list like this legal in C++11?在 C++11 中这样的初始化列表是否合法?
【发布时间】:2013-01-25 06:26:53
【问题描述】:

我阅读了 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(),

我检查了C++ support status of Clang,它看起来应该已经支持 Clang 3.1 中的 Initializer 列表。但是为什么我的代码不起作用。有人对此有想法吗?

【问题讨论】:

标签: c++ vector c++11 initialization clang


【解决方案1】:

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

Apple 的 Xcode 附带 GNU C++ 标准库 libstdc++ 的古老版本 4.2.1(有关详细信息,请参阅 https://stackoverflow.com/a/14150421/981959),该版本早于 C++11 多年,因此其 std::vector 不有一个初始化列表构造函数。

要使用 C++11 功能,您要么需要安装并使用更新的 libstdc++,要么告诉 clang 使用 Apple 自己的 libc++ 库,您可以通过 -stdlib=libc++ 选项执行此操作。

【讨论】:

  • OP 从来没有说过他在使用 Xcode,事实上这甚至没有在帖子中暗示。虽然这可能是问题所在,但结果无论如何都不是来自 Xcode。
  • @RichardJ.RossIII 我没有说他在使用 Xcode,我说 Xcode 附带 GCC 4.2.1,这是真的。错误中的标头包含路径显示标头来自 GCC 4.2.1,该版本早于 C++11。如果不是因为它是 Xcode 附带的版本,为什么会有人安装 GCC 4.2.1?
  • 感谢您的帮助!我现在明白原因了。添加-stdlib=libc++ 选项后它可以工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
  • 2013-01-23
  • 2021-12-19
  • 1970-01-01
  • 2014-07-31
相关资源
最近更新 更多