Thread: Best way to return a const char* from a string

  1. #1
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229

    Best way to return a const char* from a string

    I am trying to overload the what() method of the exception class which returns a const char*.

    What's the best way to do it if I have a std::string on the stack, storing the string I want to return?

    Obviously
    Code:
    return mystr.c_str();
    is not a good idea because mystr would be deallocated by the time the caller reads the string.

    Allocating a buffer of the same size on the stack and copying the string to it will work, but isn't that leaky? ("delete[] e.what();" just looks... wrong to me)

    What's the conventional way to go about doing this?

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Just keep an internal copy of the string:

    Code:
    class my_exception : public std::exception
    {
    	my_exception( string const& message )
    	: message( message )
    	{	}
    	
    	virtual char const* what( void ) const throw( )
    	{
    		return message.c_str( );
    	}
    	
    	virtual ~my_exception( void ) throw( )
    	{	}
    	
    	string
    		message;	
    };

  3. #3
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    Ah thanks.

    But that means the string will live only as long as the exception object? So if I have, say
    Code:
    const char *error_msg;
    try {
         //something
    } catch (my_exception &e) {
         error_msg = e.what();
    }
    //do something with error_msg
    Does it work? When does the exception object die?

  4. #4
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    The exception goes out of scope after the catch block, so you'd need something like:

    Code:
    string error_msg;
    try {
         //something
    } catch (my_exception &e) {
         error_msg = e.what();
    }
    //do something with error_msg

  5. #5
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    I see.

    Thanks for your help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. New string functions
    By Elysia in forum C Programming
    Replies: 11
    Last Post: 03-28-2009, 05:03 AM
  2. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  3. Conversion From C++ To C
    By dicon in forum C++ Programming
    Replies: 2
    Last Post: 06-10-2007, 02:54 PM
  4. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  5. "Operator must be a member function..." (Error)
    By Magos in forum C++ Programming
    Replies: 16
    Last Post: 10-28-2002, 02:54 PM