Constructing a vector<int> with 2 string literals

我的未来我决定 提交于 2020-07-18 09:47:30

问题


For the following program:

#include <vector>
#include <iostream>

int main()
{
  std::vector<int> v = {"a", "b"};
  
  for(int i : v)
    std::cout << i << " ";   
}

clang prints 97 0. The ascii value of 'a' is 97, but I don't fully understand the output.

On the other hand, gcc throws an exception:

terminate called after throwing an instance of 'std::length_error'
  what():  cannot create std::vector larger than max_size()

so I assume it's using the 2 argument constructor that takes the size and default value, where the size is computed from the address of the string literal "a".

If the program is well-formed, what is the correct behavior? Here's the code.


回答1:


I assume it's using the 2 argument constructor that takes the size and default value

No, it's using the constructor taking two input iterators. "a" and "b" could decay to pointer which is valid iterator. As the pointer (iterator) to const char, the dereferenced const char would be converted to int and added as the vector's element. Anyway the code has UB because "a" and "b" don't refer to valid range, "b" is not reachable from "a".



来源:https://stackoverflow.com/questions/62835713/constructing-a-vectorint-with-2-string-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!