Search code examples
c++stringcopy-constructorassignment-operator

Code Comparison : Which code is better to use in terms of efficiency?


Which code is better to use : to initialize string ?

bool flag = /*function call...*/
string str = "abc";
if(flag)
  str = "bcd";

Or

string str;
if(flag)
  str = "bcd";
else
  str = "abc";

Or

string str("abc");
if(flag) 
  str = "bcd";

Thanks in advance.


Solution

  • The C++ way is to use initialization:

    bool flag = foo();
    string str { flag ? "bcd" : "abc" };
    

    flag determines which string literal is used in the call to std::string::string(const char*). But there's one call, one string object being constructed, and no assignment.

    [edit] Flipped the string literals. In C++, both for the if construct and the ?: construct, the "true" case comes first, and then "false" case last. But the question had them reversed, "abc" came first for the flag==false case.