I have doubt in C++ exception :
#include <iostream>
#include <string>
using namespace std;
void some_function()
{
string str("Hello,World!");
throw(str);
}
int main()
{
try
{
some_function();
}
catch (string& e)
{
cout << e << endl;
e = "Hello, the world!";
cout << e << endl;
}
return 0;
}
debug in my PC:
some_function
the str
addr: 0x003CF820
main
the e
addr: 0x003CF738
I have three question,
string&
, why we get diff addr in main() ? str
not a temp value ? why we can use a temp value reference ?e
store in memory ?can some one help me ? thanks .
Objects that are thrown are typically copied/moved to, or directly constructed in, a memory area reserved for them - distinct from the normal function call stack and "heap". So, the address of the local str
object in some_function()
can't be expected to match the address of the string instance caught in main()
. This model allows the lifetimes of the thrown objects to be decoupled from the stack unwinding that happens until they're caught. (It also means that it may be possible - you'd want to check your implementation documentation if you cared - to throw an exception even when the remaining stack and/or heap is insufficient to store the value thrown, though many exception objects use further dynamically storage - for example, for std::string
objects with text longer than any internal short-string-optimisation buffer).
See 15.1/4:
The memory for the exception object is allocated in an unspecified way, except as noted in 3.7.4.1.
In 3.7.4.1:
[ Note: In particular, a global allocation function is not called to allocate storage for objects with static storage duration (3.7.1), for objects or references with thread storage duration (3.7.2), for objects of type std::type_info (5.2.8), or for an exception object (15.1). —end note ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With