O'Reilly logo

Essential C++ by Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.5. The Standard Exceptions

If the new expression cannot acquire memory from the program’s free store, it throws a bad_alloc exception object. For example,

vector<string>* 
init_text_vector( ifstream &infile ) 
{ 
    vector<string> *ptext = 0; 
    try { 
        ptext = new vector<string>; 
        // open file and file vector 
    } 
    catch( bad_alloc ) { 
        cerr << "ouch. heap memory exhausted!\n"; 
        // ... clean up and exit 
    } 
    return ptext; 
} 

Ordinarily, the assignment statement

ptext = new vector<string>; 

allocates the necessary memory, applies the default vector<string> constructor on the heap object, and then assigns the address of that object to ptext.

If the memory to represent a vector<string> object is not available, the default constructor is not invoked, and ptext ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required