#include #include #include #include #include #include #include // strlen strdup strcpy strncpy strcat #define T printf("%s body='%s'\n", __PRETTY_FUNCTION__, body) class str { public: str(const char *val = "") { body = strdup(val); T; } ~str() { if (body == nullptr) return; T; free(body); } void print() const { printf("[%s]\n", body); } str & operator= (const str &b) { free(body); body = strdup(b.body); T; return *this; } str(const str &b) { body = strdup(b.body); T; } #if 1 str(str &&b) { // конструктор по r-value body = b.body; // b - временный. b.body = nullptr; T; } str &operator=(str &&b) { // Копирование из r-value - можно просто забрать его поля. if (this == &b) return *this; free(body); body = b.body; b.body = nullptr; T; return *this; } #endif str operator+ (const str &b) const { T; size_t need = strlen(body) + strlen(b.body) + 1; str ret(""); ret.body = (char *)realloc(ret.body, need); assert(ret.body != nullptr); strcpy(ret.body, body); strcat(ret.body, b.body); return ret; } bool operator<(str const &oth) const { return strcmp(body,oth.body) < 0; } private: char *body; // C-string, null-terminated "123" -> '1', '2', '3', 0 }; void foo(str c) { printf("foo!"); c.print(); } #if 1 void myswap(str &l, str &r) { str t = std::move(l); l = std::move(r); r = std::move(t); } #else void myswap(str &l, str &r) { str t = l; l = r; r = t; } #endif int main() { #if 0 str a("abra"); str b("shvabra"); str c; c = a + b; myswap(a,a); a.print(); b.print(); // str c = a + b; #endif std::vector aaa; aaa.emplace_back(str("shvabra")); aaa.emplace_back(str("abra")); aaa.emplace_back(str("cadabra")); aaa.emplace_back(str("foo")); printf("======= sorting =====\n"); std::sort(aaa.begin(), aaa.end()); }