: std::string_view over const std::string& , const char* std::string . , , ( ) .
() (, , s.at(2)):
char getThird(std::string s)
{
if (s.size() < 3) throw std::runtime_error("String too short");
return s[2];
}
, . , , , () . . const:
char getThird(const std::string& s);
, std::string getThird. : , const char* ? , std::string, .
:
char getThird(const char* s)
{
if (std::strlen(s) < 3) throw std::runtime_error("String too short");
return s[2];
}
, const char*. std::string , getThird(myStr.c_str()): getThird(myStr.c_str()). , std::string , getThird , . - , checkStringForBadHacks !
, std::string . , , , ? std::strlen, , . , , , , .
std::string_view ( boost::string_view, boost::string_ref):
char getThird(std::string_view s)
{
if (s.size() < 3) throw std::runtime_error("String too short");
return s[2];
}
, , .size(), , , :
std::string, std::string_view.const char* , std::string_view.- , ,
std::string_view , , , , ( ). , const char* ( ), std::string_view std::string_view . , , , .
- , , . , .
std::string_view .
, , , std::string , , std::string_view. , , , - . :
std::string changeThird(std::string s, char c)
{
if (s.size() < 3) throw std::runtime_error("String too short");
s[2] = c;
return s;
}
std::string changeThird(std::string_view s, char c)
{
if (s.size() < 3) throw std::runtime_error("String too short");
std::string result = s;
result[2] = c;
return result;
}
, : , s , ( , std::string. , result. return , ( std::move(result)) , , .
The reason the first version might be better is because it can actually make null copies if the caller moves the argument:
std::string something = getMyString();
std::string other = changeThird(std::move(something), "x");
In this case, the first changeThirddoes not contain any copy at all, and the second -.