avoid string copies in functions like build_filename
Functions arguments of type const std::string&
and const Glib::ustring&
create unnecessary string copies if such functions are called with string literals.
Consider the current implementation of build_filename
:
std::string
build_filename(const std::string& elem1, const std::string& elem2)
{
return convert_return_gchar_ptr_to_stdstring(
g_build_filename(elem1.c_str(), elem2.c_str(), nullptr));
}
Example usage:
auto path = Glib::build_filename(dirname, "somefile");
This will create a std::string
copy of "somefile", just to pass elem2.c_str()
to g_build_filename
.
I propose to generalize the implementation and do generic forwarding of string arguments:
inline const char *c_str(const std::string &s) { return s.c_str(); }
inline const char *c_str(const ustring &s) { return s.c_str(); }
inline const char *c_str(const char *s) { return s; }
template <typename... Strings>
std::string
build_filename(const Strings&... strings)
{
return Glib::convert_return_gchar_ptr_to_stdstring(
g_build_filename(c_str(strings)..., nullptr));
}
Side-effect of such a change: Glib::build_filename(nullptr)
will not crash anymore.
Inkscape uses glibmm extensively and would benefit from such optimizations.