Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <iostream>
- #include <memory>
- #include <string_view>
- #include <utility>
- namespace {
- struct StringF {
- public:
- StringF() : StringF{0} {}
- StringF(std::string_view from) : StringF{from.size()} {
- std::copy(from.begin(), from.end(), begin());
- }
- char* begin() const { return &string_[0]; }
- char* end() const { return &string_[size_]; }
- StringF& operator+=(const StringF& right) {
- StringF concat{size_ + right.size_};
- std::copy(begin(), end(), concat.begin());
- std::copy(right.begin(), right.end(), concat.begin() + size_);
- std::swap(string_, concat.string_); // `concat` frees old `string_`
- std::swap(size_, concat.size_);
- return *this;
- }
- private:
- StringF(size_t size)
- : size_{size}, string_{std::make_unique<char[]>(size_ + 1)} {
- string_[size_] = '\0';
- }
- size_t size_;
- std::unique_ptr<char[]> string_;
- };
- std::ostream& operator<<(std::ostream& out, const StringF& in) {
- return out << in.begin();
- }
- } // namespace
- int main() {
- const StringF empty;
- const StringF space{" "};
- const StringF boo{"boo"};
- const StringF foo{"foo"};
- std::cout << empty << boo << space << foo << '\n'; // boo foo
- StringF acc;
- acc += boo;
- acc += empty;
- acc += boo;
- std::cout << acc << '\n'; // booboo
- acc += space;
- acc += foo;
- acc += empty;
- acc += foo;
- std::cout << acc << '\n'; // booboo foofoo
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement