refcountedstring/StringValue.cpp

40 lines
937 B
C++
Raw Normal View History

2016-10-23 01:46:28 +00:00
#include "StringValue.h"
#include <stdexcept>
#include <cstring>
StringValue::StringValue(char* data)
:_data(data), _size(std::strlen(data) + 1), _refs(1)
{}
void StringValue::operator++()
{ _refs++; }
void StringValue::operator--()
{
_refs--;
if (_refs == 0)
{
delete[] _data;
delete this;
/* This might seem scary, but StringValues are dynamically allocated and own themselves,
* thus when no longer referenced the object can -- and should -- commit suicide. */
}
}
const char& StringValue::operator[](size_t index) const
{
if (index > _size-1)
throw std::out_of_range("Index out of range!");
return _data[index];
}
char& StringValue::operator[](size_t index)
{ return const_cast<char&>(const_cast<const StringValue*>(this)->operator[](index)); }
StringValue::operator const char*() const
{ return _data; }
size_t StringValue::size() const
{ return _size - 1; }