bad_alloc vs nothrow

closed account (jvqpDjzh)
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';
        return true;
}

Help me to improve my code and my way of programming!
Thank you dudes!
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:


How does that reduce the code? That testing and the returning of true and false are not necessary if you use the other version of new.

Instead of
1
2
3
4
5
6
7
8
9
10
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';
        return true;
}
else
        return false;


You have:
1
2
3
4
    ptr = new char[length + 1];
    for(unsigned i=0; i<length; i++)
        ptr[i] = str[i];//str is a const char* 
    ptr[length] = '\0';


or, taking advantage of the std library facilities:
1
2
3
    ptr = new char[length + 1];
    std::copy(str, str+length, ptr);
    ptr[length] = '\0' ;

Last edited on
> 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 = new char[length + 1];

// control reaches here only if an exception was not thrown.
// rest of the code which uses ptr  
Topic archived. No new replies allowed.