When is the std::string dstor called in the following code

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • mathieu

    When is the std::string dstor called in the following code

    Hi C++ gurus,

    Why in the following code the std::string destructor is being called
    before the 'catch' ?

    Thanks,
    -Mathieu

    #include <iostream>
    #include <sstream>

    void foo()
    {
    std::ostringstr eam os;
    os << "my error";
    throw os.str().c_str( );
    }

    int main()
    {
    try
    {
    foo();
    }
    catch(const char *msg)
    {
    std::cerr << msg << std::endl;
    }
    return 0;
    }
  • Martin York

    #2
    Re: When is the std::string dstor called in the following code

    On Feb 12, 12:09 am, mathieu <mathieu.malate ...@gmail.comwr ote:
    Hi C++ gurus,
    >
    Why in the following code the std::string destructor is being called
    void foo()
    {
    .....
    throw os.str().c_str( );

    os.str() creates a std::string object and returns it as a result. As
    you are using it in an expression it is a temporary object and thus
    will be destroyed at the end of the statement.

    The value returned by c_str() is not valid beyond the lifetime of the
    object it was called on. So your best bet to actually throw the
    std::string object.
    int main()
    {
    try
    {
    foo();
    }
    Add
    catch(std::stri ng const& e)
    {
    std::cerr << e << std::endl;
    }

    catch(const char *msg)
    {
    std::cerr << msg << std::endl;
    }
    return 0;
    >
    }

    Comment

    Working...