Skip to content

Instantly share code, notes, and snippets.

@faithandbrave
Created June 11, 2024 07:12
Show Gist options
  • Save faithandbrave/b18450e1070055a375a67ca53d9e48ff to your computer and use it in GitHub Desktop.
Save faithandbrave/b18450e1070055a375a67ca53d9e48ff to your computer and use it in GitHub Desktop.
#include <string_view>
#include <memory>
#include <utility>
class life_string_view {
std::string_view _data;
std::shared_ptr<void> _life;
public:
life_string_view(std::string_view sv)
: _data{sv}, _life{} {}
life_string_view(std::string_view sv, std::shared_ptr<void> life)
: _data{sv}, _life{life} {}
template <class T>
static life_string_view allocate(T&& data) {
auto p = std::make_shared<T>(std::forward<T>(data));
return {*p, p};
}
life_string_view substr(std::size_t start, std::size_t size) {
return {_data.substr(start, size), _life};
}
friend std::ostream& operator<<(std::ostream& os, life_string_view sv) {
return os << sv._data;
}
};
#include <iostream>
life_string_view f(life_string_view sv)
{
return sv.substr(1, 3);
}
life_string_view g() {
std::string s = "Hello";
return f(life_string_view::allocate(std::move(s)));
}
int main() {
auto sv = g();
std::cout << sv << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment