Search code examples
c++stringc++11concatenation

Concatenation of std::string and int leads to a shift. Why?


Today I was surprised when trying to concatenate an std::string with an int. Consider the following MWE:

#include <iostream>
#include <string>

void print(const std::string& text)
{
    std::cout << "The string is: " << text << ".\n";
}

int main()
{
    print("iteration_" + 1);

    return 0;
}

Instead of printing

The string is: iteration_1.

which I would expect, it prints

The string is: teration_.

What exactly is going on in the background? Does the string for some reason get converted into char[] or something of the sort? The documentation of operator+ does not list any with an std::string and int.

And what is the proper way of concatenating an std::string with a number? Do I really have to throw them both into an std::stringstream or convert the number into std::string explicitely with std::to_string()?


Solution

  • Does the string for some reason get converted into char[]

    Actually it is the other way around. "iteration_" is a char[11] which decays to a const char* when you add 1. Incrementing the pointer by one makes it point to the next character in the string. This is then used to construct a temporary std::string that contains all but the first character.

    The documentation you link is for operator+ of std::string, but to use that you need a std::string first.