Created
October 12, 2012 17:21
-
-
Save klmr/3880346 to your computer and use it in GitHub Desktop.
Ultra-simple string class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef TEXT_STRING_HPP | |
#define TEXT_STRING_HPP | |
#include <algorithm> | |
#include <cstring> | |
#include <iterator> | |
#include <memory> | |
#include <iosfwd> | |
namespace text { | |
class string { | |
public: | |
typedef unsigned char value_type; | |
typedef std::size_t size_type; | |
string() : m_length(), m_buffer(new value_type[1]) { | |
m_buffer[0] = '\0'; | |
} | |
string(char const* str) | |
: m_length(std::strlen(str)) | |
, m_buffer(new value_type[m_length + 1]) | |
{ | |
std::copy(str, str + m_length + 1, &m_buffer[0]); | |
} | |
string(string const& other) | |
: m_length(other.m_length) | |
, m_buffer(new value_type[m_length + 1]) | |
{ | |
std::copy(&other.m_buffer[0], | |
&other.m_buffer[m_length] + 1, | |
&m_buffer[0]); | |
} | |
string(string&& other) /*noexcept*/ = default; | |
string& operator =(string other) noexcept { | |
m_length = std::move(other.m_length); | |
m_buffer = std::move(other.m_buffer); | |
return *this; | |
} | |
//string& operator =(string&&) noexcept = default; | |
size_type length() const { return m_length; } | |
friend std::ostream& operator <<(std::ostream& out, string const& str) { | |
std::copy(&str.m_buffer[0], | |
&str.m_buffer[str.length()], | |
std::ostream_iterator<char>(out, "")); | |
return out; | |
} | |
private: | |
size_type m_length; | |
std::unique_ptr<value_type[]> m_buffer; | |
}; | |
} // namespace text | |
#endif // ndef TEXT_STRING_HPP |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "string.hpp" | |
#define DEBUG(str) std::cout << "> " << #str << " = \"" << str << "\"\n" | |
void f(text::string&& str) { | |
DEBUG(str); | |
} | |
int main() { | |
using text::string; | |
using std::cout; | |
string s1; | |
string s2 = "Hello"; | |
DEBUG(s1); | |
DEBUG(s2); | |
s1 = s2; | |
cout << "s1 = s2\n"; | |
DEBUG(s1); | |
DEBUG(s2); | |
s1 += " world"; | |
cout << "s1 += \" world\"\n"; | |
DEBUG(s1); | |
DEBUG(s2); | |
string s3(s1); | |
cout << "string s3(s1)\n"; | |
DEBUG(s1); | |
DEBUG(s2); | |
DEBUG(s3); | |
string s4 = std::move(s3); | |
s1 = std::move(s2); | |
cout << "string s4 = std::move(s3)\n"; | |
cout << "s1 = std::move(s2)\n"; | |
DEBUG(s1); | |
DEBUG(s2); | |
DEBUG(s3); | |
DEBUG(s4); | |
cout << "f(\"test\")\n"; | |
f("test"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment