Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return std::strings?

I'm trying to use std::string instead of char* whenever possible, but I worry I may be degrading performance too much. Is this a good way of returning strings (no error checking for brevity)?

std::string linux_settings_provider::get_home_folder() {     return std::string(getenv("HOME")); } 

Also, a related question: when accepting strings as parameters, should I receive them as const std::string& or const char*?

Thanks.

like image 769
Pedro d'Aquino Avatar asked Jun 23 '09 12:06

Pedro d'Aquino


People also ask

Should I use std::string?

h functions when you are declaring string with std::string keyword because std::string strings are of basic_string class type and cstring strings are of const char* type. Pros: When dealing exclusively in C++ std:string is the best way to go because of better searching, replacement, and manipulation functions.

What does std::string end () return?

std::string::end Returns an iterator pointing to the past-the-end character of the string. The past-the-end character is a theoretical character that would follow the last character in the string.

Can you return a string C++?

Use the std::string func() Notation to Return String From Function in C++ Return by the value is the preferred method for returning string objects from functions. Since the std::string class has the move constructor, returning even the long strings by value is efficient.

Can strings be returned?

Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid.


1 Answers

Return the string.

I think the better abstraction is worth it. Until you can measure a meaningful performance difference, I'd argue that it's a micro-optimization that only exists in your imagination.

It took many years to get a good string abstraction into C++. I don't believe that Bjarne Stroustroup, so famous for his conservative "only pay for what you use" dictum, would have permitted an obvious performance killer into the language. Higher abstraction is good.

like image 102
duffymo Avatar answered Sep 22 '22 13:09

duffymo