在以下代码里,除了最后赋值给成员变量,中间所有步骤都无须拷贝
=================================================================
class Person {
public:
bool SetName(string_view name) {
if (name.empty()) {
return false;
}
auto [first_name, last_name] = GetFirstLastName(name);
if (!ValidateFirstName(first_name) || !ValidateLastName(last_name)) {
return false;
}
first_name_ = first_name;
last_name_ = last_name;
return true;
}
private:
// Return value is only valid if the input string is still in lifetime.
pair<string_view, string_view> GetFirstLastName(string_view name) {
int i = 0;
while (i < name.size() && name[i] != ' ') {
++i;
}
string_view first_name = name.substr(0, i);
string_view last_name = name.substr(i);
return {first_name, last_name};
}
bool ValidateFirstName(string_view) {
// TODO: add real validation logic.
return true;
}
bool ValidateLastName(string_view) {
// TODO: add real validation logic.
return true;
}
string first_name_;
string last_name_;
};
int main() {
Person p;
p.SetName("James Bond");
string request = "AGENT:James Bond"; // suppose this data is coming from outside source.
constexpr string_view agent = "AGENT:";
string_view r = request;
CHECK(r.starts_with(agent));
r.remove_prefix(agent.size());
p.SetName(r);
return 0;
}
--
修改:here080 FROM 76.126.252.*
FROM 76.126.252.*