Search code examples
c++stringc++11uniform-initialization

std::string(count, ch) not called when using uniform initialization


I just got caught by this seemingly innocent attempt to call the std::string constructor that takes a size and a character value, using uniform initialization syntax:

std::string s{ 10, '\0' };

I thought this would create a string with the length of 10, initialized with \0.

Though it actually calls the constructor that takes an initializer list and thus creates a string with the length of 2, initialized with {'\n', '\0'}!

See demo at Coliru.

Is there a way to avoid this pitfall when using uniform initialization? Or do I just have to be careful?

Note: Similar question has been asked before, but no answer was given on how to avoid that pitfall.


Solution

  • You just have to be careful.

    In general, when people tell you to "use uniform initialisation so that everything is consistent and, well, uniform", ignore them. I mean, by all means use uniform initialisation, but don't believe that fairytale.

    Also, ignore the name of the feature.

    xkcd #927: "Standards"