File size: 1,517 Bytes
d1be154 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | #pragma once
#include <memory>
#include <string>
namespace tf {
class LazyString {
public:
LazyString() = default;
LazyString(const std::string& str) :
_str(str.empty() ? nullptr : std::make_unique<std::string>(str)) {
}
LazyString(std::string&& str) :
_str(str.empty() ? nullptr : std::make_unique<std::string>(std::move(str))) {
}
LazyString(const char* str) :
_str((!str || str[0] == '\0') ? nullptr : std::make_unique<std::string>(str)) {
}
// Modify the operator to return a const reference
operator const std::string& () const noexcept {
static const std::string empty_string;
return _str ? *_str : empty_string;
}
LazyString& operator = (const std::string& str) {
if(_str == nullptr) {
_str = std::make_unique<std::string>(str);
}
else {
*_str = str;
}
return *this;
}
LazyString& operator = (std::string&& str) {
if(_str == nullptr) {
_str = std::make_unique<std::string>(std::move(str));
}
else {
*_str = std::move(str);
}
return *this;
}
bool empty() const noexcept {
return !_str || _str->empty();
}
size_t size() const noexcept {
return _str ? _str->size() : 0;
}
friend std::ostream& operator<<(std::ostream& os, const LazyString& ls) {
os << (ls._str ? *ls._str : "");
return os;
}
private:
std::unique_ptr<std::string> _str;
};
} // end of namespace tf -------------------------------------------------------------------------
|