Skip to content

Instantly share code, notes, and snippets.

@LucianoPAlmeida
Created December 1, 2021 02:27
Show Gist options
  • Save LucianoPAlmeida/6e0f9fda44a6954ae26ced71548ed350 to your computer and use it in GitHub Desktop.
Save LucianoPAlmeida/6e0f9fda44a6954ae26ced71548ed350 to your computer and use it in GitHub Desktop.
class A {
std::vector<std::string> _values;
public:
void addValue(const std::string &val) {
// some logic
_values.emplace_back(val);
}
void addValue(std::string &&val) { // r-value ref overload
// some logic
_values.emplace_back(std::move(val)); // We know that is a r-value
}
};
// Not only overload resolution will be able to pick the r-value overload for calls being made with r-value arguments,
// but we will be also allowed to use this when we know is the last usage of a value. Example
A a;
for (...) {
std::string s = compute(...);
a.addValue(std::move(s)); // Since is the last use of s, it is safe and more efficient to just move.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment