5

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:

  1. in some_function the str addr: 0x003CF820
  2. int main the e addr: 0x003CF738

I have three question,

  1. catch parameter is string&, why we get diff addr in main() ?
  2. is str not a temp value ? why we can use a temp value reference ?
  3. where is e store in memory ?

can some one help me ? thanks .

Jerry Zhang
  • 1,198
  • 1
  • 17
  • 36
  • 2
    See here: https://stackoverflow.com/questions/1654150/scope-of-exception-object-in-c –  Jan 07 '14 at 08:07
  • That question is not a duplicate but the [top answer](http://stackoverflow.com/a/1654187/15416) there also covers this question. – MSalters Jan 07 '14 at 09:56

1 Answers1

12

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 ]

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252