Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdlib>
- // using std::free
- #include <string_view>
- #include <utility>
- // using std::exchange
- class CSView
- {
- std::string_view view;
- public:
- explicit CSView(char* ptr) noexcept
- : view(ptr)
- {}
- CSView(CSView&& o) noexcept
- : view(std::exchange(o.view, std::string_view{}))
- {}
- ~CSView()
- { std::free(const_cast<char*>(view.data())); }
- void swap(CSView& o) noexcept
- { view.swap(o.view); }
- friend void swap(CSView& left, CSView& right) noexcept
- { left.swap(right); }
- CSView& operator=(CSView&& o) noexcept
- {
- CSView tmp = std::move(o);
- swap(tmp);
- return *this;
- }
- const std::string_view& operator*() const noexcept
- { return view; }
- const std::string_view* operator->() const noexcept
- { return &view; }
- };
- #include <cstring>
- // using std::strcpy
- #include <iostream>
- // using std::cout
- int main()
- {
- char* ptr = static_cast<char*>(std::malloc(80));
- std::strcpy(ptr, "Hello World\n");
- CSView cs { ptr };
- std::cout << "World at " << cs->find("World")
- << " in " << *cs;
- }
Advertisement