Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

It works, no crashes. Is it OK?

edit: the reason I ask is that std::string s = "a" + "b" + "c"; produces a compiler error, and (std::string)"a" just tells the compiler, "Just presume what "a" is pointing at is an std::string". And I didn't actually know how std::string is implemented.

Thanks for the feedback from everyone.

like image 752
Mark Avatar asked Dec 06 '22 23:12

Mark


2 Answers

Yes. + is left-associative, so it's equivalent to ((std::string)"a" + "b") + "c". std::string::operator+ is overloaded to take a const char * as the argument.

like image 157
Oliver Charlesworth Avatar answered Dec 09 '22 13:12

Oliver Charlesworth


Yes. That's fine.

It's mostly equivalent to doing

std::string s = "a";
s += "b";
s += "c";
like image 27
Bill Lynch Avatar answered Dec 09 '22 12:12

Bill Lynch