1

Just asking, is this still undefined behavior?

vecExplode is actually still returning a std::vector<std::string> value, but loading it as a reference seems wrong, just asking if (even though useless) it can still be undefined..?

std::vector<std::string> vecExplode(const std::string& str, const char ch, const bool allowEmpty)
{
    std::string next;
    next.reserve(1024);
    std::vector<std::string> result;
    result.reserve(16);
    // Check if it even exists. If not, return result instantly
    
    for (auto it = str.begin(); it != str.end(); ++it)
    {
        const char pStr = *it;
        if (pStr == ch)
        {
            if (!next.empty() || allowEmpty)
            {
                result.push_back(next);
                next = "";
            }
        }
        else
        {
            next += pStr;
        }
    }
    if (!next.empty())
        result.push_back(next);

    return result;
}

void func()
{
     const std::vector<std::string>& args = vecExplode(someString, ' ');
}

This is just a question.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
zeronull
  • 21
  • 2
  • 5
    Never has been UB, but it is also tricky to rely on const& extending the lifefime of the return value. Bboundary conditions do apply: E.g https://abseil.io/tips/107 – Pepijn Kramer May 07 '23 at 08:55
  • 2
    Technically correct, but - as you say - pretty useless. The compiler would have to store the vector somewhere anyway, and then also create a reference. Seems like a net loss. If I were to learn C++ now, I would focus on the useful parts and skip the rest. :-) Nobody knows *all* of C++ anyway, [not even Bjarne](https://www.youtube.com/watch?v=VI21tpdkHA8&t=3469s). – BoP May 07 '23 at 10:16
  • *Just asking, is this still undefined behavior?* When was this ever undefined behavior? – Eljay May 07 '23 at 13:41
  • I would no more write like this. With ranges, it is going to be a one-liner. It just a `split | filter | to`. – Red.Wave May 08 '23 at 08:26

0 Answers0