c++stringstdbraced-init-list

Is std::string an array of two iterators?


I do not understand the behavior of the following snippet. How could this be happening?

#include <bits/stdc++.h>
using namespace std;
int main() {
  string s = "apple";
  string foo = {s.begin(), s.end()};
  cout <<  foo << endl;
}

output: apple


Solution

  • Don't confuse how an object is constructed over what it fundamentally is.

    A constructor can, and will, take in all kinds of things. Quite often these arguments are converted in some way, transformed into the form that's a more natural fit for the class in question.

    In this case you're constructing a string out of a range of characters, or in other words, an arbitrary substring. There are many other methods, including converting from char*, which is something you'll see all the time:

    std::string example = "example";
    

    Here you can read that as "example is initialized with the value "example"".