Std :: string s = (std :: string) "a" + "b" + "c"; OK?

It works, no glitches. Everything is good?

edit: the reason I'm asking is because std::string s = "a" + "b" + "c"; creates a compiler error, and (std::string)"a" simply tells the compiler: "Just assume that" a "points to std :: string." And I really did not know how std :: string is implemented.

Thanks for the feedback from everyone.

+4
source share
5 answers

Yes. + left associative, so it is equivalent to ((std::string)"a" + "b") + "c" . std::string::operator+ overloaded to accept const char * as an argument.

+6
source

Yes. It's fine.

This is basically equivalent to doing

 std::string s = "a"; s += "b"; s += "c"; 
+5
source

(std::string)"a" just tells the compiler: "Just suppose that "a" points to std::string "

No, this is not what distinguishes the type of object in general. Casting to an object type is an explicit conversion request. (std::string)"a" means "build a temporary std::string from a literal ( const char[] ) "a" .

In the declaration std::string s = (std::string)"a" + "b" + "c"; this temporary resource is stored until the initialization of s completed. (12.2 [class.temporary] / 4)

There are (at least) two subsequent timelines, the result of applying operator+ to the first temporary and "b" and the result of applying operator+ to this temporary and "c2" . This last temporary value is used for copy-initialize s . Upon completion of initialization, all temporary files are destroyed in the reverse order of their construction.

Initialization is valid and has the correct behavior.

+2
source

std::string has a member function operator + , which takes a right argument of type const char * . There is also a globally defined operator + that allows const char * be on the left side of the operator.

 // std::string::operator + (const char *) std::string a; a = "b"; // global operator + (std::string, const char *) std::string a; a = (std::string)"b" + "c"; // global operator + (const char *, std::string) std::string a; a = "b" + (std::string)"c"; 

The reason the argument must be of type std::string is because string literals are of type const char * . The problem with doing "a" + "b" is that the compiler does not have objects of type std::string in the assignment statement and therefore tries to add pointers together. To avoid this, you should have a term like std::string left or right side of the char * term.

+1
source

Would be better:

 std::string s(std::string("a") + "b" + "c"); 
+1
source

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


All Articles