I just stumbled over Evan Teran's answer on Split a string in C++?, in which he takes a vector by reference, modifies it and returns a reference of it.
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
Is this good style? I see that the advantage is to directly use the result, like in
std::vector<std::string> vec;
unsigned int uiSize = split("ssad asda", ' ', vec).size();
instead of
std::vector<std::string> vec;
split("ssad asda", ' ', vec);
unsigned int uiSize = .size()
Are there any disadvantages? As far as I know, the main reason against returning references is that people might return a reference of a local variable which is destructed after the return. This does not apply here, as the object is not local but given to the method as a parameter.