Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

return values instead of passing by reference #13

Open
paulpach opened this issue Jun 15, 2017 · 1 comment
Open

return values instead of passing by reference #13

paulpach opened this issue Jun 15, 2017 · 1 comment

Comments

@paulpach
Copy link

    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/

@kymo
Copy link
Owner

kymo commented Jun 17, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants