vendredi 12 juillet 2019

C++ splitting a String feedback

I am new to C++ and I still have trouble understanding when I should use pointers, references, std::move. I have programmed a short function to split strings using a delimiter.

std::vector<std::string> mylib::split(std::string string, char delimiter) {
    std::vector<std::string> result = std::vector<std::string>();

    std::string cache = std::string();
    cache.reserve(string.size());

    for (char c : string) {
        if (c == delimiter) {
            result.push_back(std::string(cache));
            cache.clear();
        } else {
            cache += c;
        }
    }
    cache.shrink_to_fit();
    result.push_back(cache);
    return result;
}

I have a few questions to this function: Should I use

std::vector<std::string> mylib::split(std::string string, char delimiter) {

or

std::vector<std::string> mylib::split(std::string &string, char delimiter) {

and should it be

result.push_back(std::string(cache));

or

result.push_back(std::move(std::string(cache)));

And do I have to care about the destruction of any of the used objects or could I use this function just like that? Also, if there are any other ways to improve this method I would be happy to hear your ideas.

Aucun commentaire:

Enregistrer un commentaire