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

M

mathieu

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::eek:stringstream os;
os << "my error";
throw os.str().c_str();
}

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

Martin York

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::string const& e)
{
std::cerr << e << std::endl;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,152
Members
46,697
Latest member
AugustNabo

Latest Threads

Top