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
|
// User-defined size; last character reserved for \0
#define MAX_CSTR_SIZE 100
struct CStr
{
// Note: Buffer is zero-filled.
CStr(void)
{
cstr = new char[MAX_CSTR_SIZE];
memset(cstr, 0, MAX_CSTR_SIZE);
}
// Construct a CStr from a c-string
// Truncate-copy the c-string, up to MAX_CSTR_SIZE-1 chars.
CStr(char *ptr) : CStr()
{
strncpy(cstr, ptr, strlen(ptr));
}
~CStr()
{
free(cstr);
}
// Copy assignment
CStr& operator=(CStr &rhs)
{
// This is definition is problematic if "this" cstring is default-constructed. The buffer is allocated
// but since it's zero-filled, strlen(this->cstr) and thus smallerSz will evaluate to 0. strncpy
// will copy 0 bytes from rhs.cstr into this->cstr. In this case, copy the entire buffer of the smaller
// of the two CStr types.
if (strlen(this->cstr) == 0)
{
// Can't compare the size because it's not templated. So copy all MAX_CSTR_SIZE-1 bytes.
strncpy(cstr, rhs.cstr, MAX_CSTR_SIZE-1);
cstr[MAX_CSTR_SIZE-1] = '\0';
return *this
}
size_t smallerSz = std::min(strlen(cstr), strlen(rhs.cstr));
strncpy(cstr, rhs.cstr, smallerSz);
return *this;
}
char *cstr;
};
bool operator!(const CStr& lhs, const CStr&rhs)
{
if (!lhs.cstr || !rhs.cstr) return false;
return strcmp(lhs.cstr, rhs.cstr);
}
|