2013-02-09 88 views
4

我读了C++ primer第5版,它说最新的标准支持列表初始值设定项。初始化程序列表在C++ 11中是否合法?

我的测试代码是这样的:

#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; 
} 

然后我用锵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,它看起来应该已经支持Cla 3.1中的初始化程序列表。但为什么我的代码不起作用。有没有人有关于此的想法?

+1

我想这只是没有更新库的初始化列表构造函数。 – chris 2013-02-09 16:51:36

+0

@chris谢谢!有没有办法轻松更新库? – 2013-02-09 16:53:42

+0

我不能说。不幸的是,我已经在Windows上完成了所有的工作,没有Clang。 – chris 2013-02-09 16:57:20

回答

6

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

Apple的Xcode附带了GNU C++标准库的古老版本4.2.1,libstdC++(详细请参阅https://stackoverflow.com/a/14150421/981959),该版本在C++ 11之前多年发布,因此它的std::vector没有初始化程序 - 列表构造函数。

要使用C++ 11功能,您需要安装并使用更新的libstdC++,或告诉clang使用Apple自己的libC++库,您可以使用-stdlib=libc++选项。

+0

OP从未说过他使用的是Xcode,实际上这在帖子中并没有暗示。虽然这可能是问题,但结果并非来自Xcode。 – 2013-02-09 17:02:14

+0

@乔纳森抛开问题..是这本书是好的。 – Arpit 2013-02-09 17:02:38

+5

@ RichardJ.RossIII我没有说他在使用Xcode,我说Xcode附带GCC 4.2.1,这是真的。头文件包括错误显示的头文件,头文件来自GCC 4.2.1,它在C++ 11之前进行。如果不是因为它是Xcode附带的版本,为什么其他人会安装GCC 4.2.1? – 2013-02-09 17:04:27