I am writing my String class, just to practice, but I would like to create something at least not bad. I am using pointers (C-Strings) to internally represent the string, but I have to face many times the operator new and delete[].
In your opinion, what should I use the nothrow new version or the bad_alloc one? In what circumstances? I have heard that internally the std::string is implemented using the standard version of new, which is to throw an exception of type of bad_alloc. What I have done until now is use (std::nothrow), which reduces a bit the code, but is it best? Is this the right way:
1 2 3 4 5 6 7 8
ptr = new (std::nothrow) char[length + 1];//Or allocates or returns nullptr
if(ptr)
{
for(unsigned i=0; i<length; i++)
ptr[i] = str[i];//str is a const char*
ptr[length] = '\0';
returntrue;
}
Help me to improve my code and my way of programming!
Thank you dudes!
> what should I use the nothrow new version or the bad_alloc one?
Use the default (throwing) new and let the exception propagate to the user of the String class.
(Allow the user of your String class to decide how to handle an out of memory situation.)
1 2 3 4 5
ptr = nullptr ; // to put the object to a safely destructible state if new throws
ptr = newchar[length + 1];
// control reaches here only if an exception was not thrown.
// rest of the code which uses ptr