2013-06-10 19 views
0

코드 고려해C++ 11 initializer_list 오류

#include <iostream> 
#include <vector> 
#include <string> 

int main() 
{ 
    std::vector<std::string> v{{"awe", "kjh"}}; // not v{"awe", "kjh"} 

    std::cout << v.size() << std::endl; 

    return 0; 
} 
  1. 이 코드는 잘못인가? 아니면 벡터를 초기화하는 동안 double {}을 사용하는 것이 맞습니까?

  2. gcc와 MSVC에서이 코드를 시도했습니다. MSVC 2012 + 컴파일러 2011 년 11 월 컴파일 할 수 없습니다. 놀라운 일이 아닙니다. gcc 4.7 또는 4.8로 컴파일 된이 코드는 프로그램 실행 중 런타임 오류 을 제공합니다. 이 행동이 맞습니까?

다른 컴파일러로는 테스트 할 수 없습니다.

+0

이 유용 할 수 있습니다 - http://stackoverflow.com/questions/11400090/c-why-initializer-list-behavior-for-stdvector-and-stdarray-are-different – Bill

+0

참조 http://stackoverflow.com/questions/14587436/call-of-overloaded-brace-enclosed-initializer-list-is-ambiguous-how-to-deal-w 및 http://cplusplus.github.io/ LWG/lwg-active.html # 2238 (이 광고는 다른 광고와 관련이 있지만 매우 유사합니다.) –

답변

3

참고 할 경우 런타임에 실패합니다 : 표준 유형 std::string의 구현과 같은 생성자를 필요로하지 않습니다

std::vector<std::string> v{std::string{"awe", "kjh"}}; 
// not: std::vector<std::string> v{std::string{"awe"}, std::string{"kjh"}}; 

를, 그래서를 기반으로 특정 성병 구현, 나는 코드가 다른 일을 할 수 있다고 생각합니다.

감사합니다, & rzej

1

내부 {}은 std :: string 생성자로 취급되고 있습니다. 당신은 당신의 초기화에 해당

std::string> s{"awe", "kjh"};