SUNET icon indicating copy to clipboard operation
SUNET copied to clipboard

return values instead of passing by reference

Open paulpach opened this issue 7 years ago • 1 comments

    static void split(const std::string& str, 
            const std::string& delim,
            std::vector<std::string>& ret) {
        if (str.size() <= 0 || delim.size() <= 0) {
            ret.clear();
            return;
        }
        ret.clear();
        int last = 0;
        int index = str.find_first_of(delim, last);
        while (index != -1) {
            ret.push_back(str.substr(last, index - last));
            last = index + 1;
            index = str.find_first_of(delim, last);
        }
        if (index == -1 && str[str.size() - 1] != '\t') {
            ret.push_back(str.substr(last, str.size() - last));
        }
    }

instead of passing the vector by reference, simply return it like this:

    static std::vector<std::string> split(const std::string& str, 
            const std::string& delim) {
        std::vector<std::string> ret;

        if (str.size() <= 0 || delim.size() <= 0) {
            return ret;
        }
        int last = 0;
        int index = str.find_first_of(delim, last);
        while (index != -1) {
            ret.push_back(str.substr(last, index - last));
            last = index + 1;
            index = str.find_first_of(delim, last);
        }
        if (index == -1 && str[str.size() - 1] != '\t') {
            ret.push_back(str.substr(last, str.size() - last));
        }
        return ret;
    }

This code is much easier to read. The compiler optimizes this to be equivalent to the previous code. This is known as RVO https://en.wikipedia.org/wiki/Return_value_optimization and pretty much all compilers do it. See benchmarks here http://rohankshir.github.io/2015/05/01/return-value-optimization/

paulpach avatar Jun 15 '17 16:06 paulpach

I am really aprreciate your comments about these raw codes,I will do my best to improve it. Thanks a lot :)

kymo avatar Jun 17 '17 03:06 kymo