coin cheung
coin cheung

Reputation: 1107

How could I assign a c++ string to another by its reference

I have two c++ strings std::string dir_1("./dir1"); std::string dir_2("./dir2"); which I need to assign them to another string according to some conditions: if (...) str = dir_1; else str = dir_2;.

However, this operations will copy the contents of dir_1 and dir_2 which brings some overhead. How could I reduce this overhead ? Is it possible that I only implement the assignment via their references ?

Upvotes: 1

Views: 424

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93324

Make str a reference and use the ternary operator to initialize it:

const std::string& str = condition ? dir_1 : dir_2;

This will not require and copy or move of the original strings.


If the condition is more complicated, you can use IIFE (immediately-invoked function expression):

const std::string& str = []() -> auto&
{
    if(condition) return dir_1;
    else return dir_2;
}();

Or simply refactor the initialization logic to a different function.

Upvotes: 6

Related Questions