Hi,
I'm looking at a legacy string class thats been in use here for a while
and I'd like to check out any options available to optimise it. I see a
couple of constructors that look dubious. Consider the following ctor.
It constructs a TtkString object with a string value of the integer
contained withing. e.g
TtkString one(456);
cout << one << endl;
prints;
456
// "string" is declared as a const char* within the class
TtkString::TtkString(int i)
{
std::stringstream s;
s << i << std::ends;
std::string myString = s.str();
const char* localString = myString.c_str();
int size(strlen(localString));
string = (char *) malloc((size + 1)*sizeof(char)) ;
memset(string,0,size+1);
strncpy(string, localString,size);
}
reading the code below I see that stringstreams are used (which seems
to me to be a bit heavyweight) and in addition a std::string is
constructed just to get the resulting const char*, subsequently the
malloc is done followed by a memset and a strcpy. It all seems a little
heavy to me (but I stand open to correction...perhaps this is not such
a bad approach altogether).
I was considering using something like this for the body of the same
function....
string = (char*) calloc (1, 33); // 32 bit system assumed.
memset(string,0,33);
itoa(i, string, 10);
however this is not working....Ive obviously messed something up. Can
anybody shed some light? My approach allocates 33 bytes regardless of
what the "i" argument is... e.g if its 1 then I don't need all 33
bytes, do I really?
If there are examples of this implemented in some library such as boost
or whatever, I'd be keen to check them out to see how they do it and
where my mistake is.
Finally, this constructor is overloaded to take floats, doubles , longs
etc and they all work more or less on the same approach. If I can
optimise this, I can optimise them all.
thanks for any assistance/input.
have a nice day.
G