|
| 1 | +#include <cstdio> |
| 2 | +#include <string> |
| 3 | +#include <utility> |
| 4 | + |
| 5 | +static void print_moved_from(const char *label, const std::string &from, |
| 6 | + const std::string &to) { |
| 7 | + std::string sub = from.substr(0, 0); |
| 8 | + printf("%s: %zu %zu %d %zu %d [%s]\n", label, from.size(), sub.size(), |
| 9 | + from.c_str()[0], to.size(), sub.c_str()[0], to.c_str()); |
| 10 | +} |
| 11 | + |
| 12 | +static std::string return_local() { |
| 13 | + std::string word = "returned local"; |
| 14 | + return (word); |
| 15 | +} |
| 16 | + |
| 17 | +static std::string return_parameter(std::string word) { return word; } |
| 18 | + |
| 19 | +static std::string return_reference(std::string &word) { |
| 20 | + return std::move(word); |
| 21 | +} |
| 22 | + |
| 23 | +static std::string return_rvalue_reference(std::string &&word) { return word; } |
| 24 | + |
| 25 | +int main() { |
| 26 | + std::string empty; |
| 27 | + std::string from_empty(std::move(empty)); |
| 28 | + print_moved_from("construct empty", empty, from_empty); |
| 29 | + |
| 30 | + std::string word = "hello"; |
| 31 | + std::string from_word(std::move(word)); |
| 32 | + print_moved_from("construct word", word, from_word); |
| 33 | + |
| 34 | + std::string long_word = "a string that does not fit in place"; |
| 35 | + std::string assigned = "x"; |
| 36 | + assigned = std::move(long_word); |
| 37 | + print_moved_from("assign long", long_word, assigned); |
| 38 | + |
| 39 | + std::string short_word = "ab"; |
| 40 | + std::string assigned_short; |
| 41 | + assigned_short = std::move(short_word); |
| 42 | + print_moved_from("assign short", short_word, assigned_short); |
| 43 | + |
| 44 | + word.append("again", 5); |
| 45 | + printf("reuse: %zu %s\n", word.size(), word.c_str()); |
| 46 | + std::string local = return_local(); |
| 47 | + std::string parameter = return_parameter("returned parameter"); |
| 48 | + printf("returns: %s %s\n", local.c_str(), parameter.c_str()); |
| 49 | + |
| 50 | + std::string source = "returned reference"; |
| 51 | + std::string reference = return_reference(source); |
| 52 | + print_moved_from("return reference", source, reference); |
| 53 | + |
| 54 | + source.append("rvalue reference", 16); |
| 55 | + std::string rvalue_reference = return_rvalue_reference(std::move(source)); |
| 56 | + print_moved_from("return rvalue reference", source, rvalue_reference); |
| 57 | + return 0; |
| 58 | +} |
0 commit comments