Search code examples
c++copyconditional-operator

Avoid unnecessary copy in ternary operator


My understanding in that the type that the ternary operator evaluates to in the following function is std::string, i.e. it's a value, not a reference.

Is there a trick to avoid copying the string when the first branch is evaluated?

bool f(const std::vector<std::string>& vec, const std::string& s) {
    const std::string& s2 = !s.empty() && s[0] == '{' ? s : '{' + s + '}';
    for (const std::string& v : vec) {
        if (v == s2)
            return true;
    }
    return false;
}

EDIT:

Looks like I formulated the question too specifically. I meant for the code with strings to just be an example. The question I had in mind is more general. If you need a potential expensive modification for a large object, but, if a condition is met, could use the object as is, is there a way to bind either the original object or the result of the computation to a reference, without copying the original object if the computation is not required?


Solution

  • Is there a trick to avoid copying the string when the first branch is evaluated?

    Not with the tenary operator alone, no. But you can break out the search loop separately so you can pass a search string by reference to it, and then use the operator to invoke the loop with the desired search string, eg:

    bool f(const std::vector<std::string>& vec, const std::string& s) {
    
        auto findIt = [&vec](const std::string& s) {
            for (const std::string& v : vec) {
                if (v == s)
                   return true;
            }
            return false;
            // or simply:
            // return std::find(vec.begin(), vec.end(), s) != vec.end();
        };
    
        return (!s.empty() && s[0] == '{')
            ? findIt(s)
            : findIt('{' + s + '}');
    }