What exactly happens when a character is added to a string literal using the "+" operator in C ++?

Based on my reading, the following code:

string aggregate = "give" + 'n'; 

Should create a result line with the value:

"given".

Instead, it produces garbage. Why doesn't the following happen?

  • "give" is converted to std :: string through a constructor that takes a pointer to an array of characters.

  • An overload of '+' is called, which takes std :: string and a character, returning a new line.

I base my theory on this manual page.

Now I heard that the first argument of the overloaded operator is not a candidate for constructor conversion if the operator is a member of the class. In my opinion, I read this in Koenig and Mu. But in this case, I understand that the + operator is a non-member overload.

I understand that this sounds like a ridiculous over-complication, but I like to know FOR SURE what happens when I write code.

+4
source share
4 answers

First, the expression "give" + 'n' is evaluated, adding (int)'n' to the address of the string constant "give" . The result of this arithmetic pointer is assigned to a string object. The error does not occur because the result is of type const char* .

You should get used to thinking about everything that is to the right of = , as it happens before the actual assignment (or initialization in this case).

You want the following:

 // construct the string object first std::string aggregate = "give"; // then append the character aggregate += 'n'; 

or, explicitly first create a string object:

 std::string aggregate = std::string("give") + 'n'; 
+6
source

The fact that there is std::string on the left side of the expression does not matter for the first step: "give" is a const char[5] , which splits into a const char* and 'n' is char , that is, an integer type . Adding an integer to a pointer simply adds the address of the pointer. The result is again of type const char* , which is then implicitly converted to std::string .

Basically, your code is equivalent to:

 const char* c = "a string" + 'n'; std::string s = c; 

So, to achieve the desired effect, try

 std::string s = std::string("a string") + 'n'; 
+4
source

You add the integer "n" to the literal address "give".

Try:

 string aggregate = "long string long string long string long string long string long string long string " + 'A'; 

This should illustrate what is happening.

+2
source

This code does not do what you think.

It takes the string literal "give" , which then degrades effectively into const char[5] , and then adds the integer value 'n' to this pointer. Then he takes this new garbage pointer and tries to make a string out of it.

You want string aggregate = std::string("give") + 'n';

+1
source

Source: https://habr.com/ru/post/1343222/


All Articles