c++ - std::exception using message from local object -


is following code safely throwing exception custom message?

#include <exception> #include <sstream> #include <string> #include <iostream>  int main() {   try {     std::ostringstream msg;     msg << "give me " << 5;     throw std::exception(msg.str().c_str());   } catch (std::exception& e) {     std::cout << "exception: " << e.what();   } } 

with vc++-2008 gives:

exception: give me 5 

but wonder why message "give me 5" local object msg still available in catch-block? time message printed both stream- , temporary string-object should have been deleted? btw: way of generating message exception seems work accross several functions , if new memory allocated in catch-block before printing exception.

or necessary define custom exception class std::string member in order safely keep message until printing it.

it's safe. constructor takes c string single parameter makes copy of string. constructor takes c string , length parameter allow specify no memory allocated , stores pointer string (the length parameter ignored).

note these 2 constructors extensions std::exception class , not standard. aware constructor takes c string single parameter not marked explicit.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -