0

Consider the code:

#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. Is this code erroneous? Or may be it is valid to use double {} while initializing vector?

  2. I tried this code on gcc and MSVC. MSVC 2012 + complier Nov 2012 just cannot compile it, it is not surprising. This code compiled with gcc 4.7 or 4.8 gives a runtime error during program execution. Is this behavour correct?

Unfortuantely can not test it with other compilers.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
inkooboo
  • 2,904
  • 1
  • 19
  • 24
  • this may be useful - http://stackoverflow.com/questions/11400090/c-why-initializer-list-behavior-for-stdvector-and-stdarray-are-different – Bill Jun 10 '13 at 15:29
  • see http://stackoverflow.com/questions/14587436/call-of-overloaded-brace-enclosed-initializer-list-is-ambiguous-how-to-deal-w and http://cplusplus.github.io/LWG/lwg-active.html#2238 (they concern something else than this one, but very similar). – Johannes Schaub - litb Jun 10 '13 at 21:06

2 Answers2

3

Note that your initialization is equivalent to:

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

The Standard does not require such a constructor of implementations of type std::string, so based on a particular STD implementation, I guess the code can do different things.

Regards, &rzej

Andrzej
  • 5,027
  • 27
  • 36
1

The inner {} is being treated a a std::string constructor. It will fail at runtime if you just do

std::string> s{"awe", "kjh"};
doctorlove
  • 18,872
  • 2
  • 46
  • 62