Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where C++ exception parameter store in memory?

Tags:

c++

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 .

like image 728
Jerry Zhang Avatar asked Jan 07 '14 08:01

Jerry Zhang


1 Answers

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 ]

like image 162
Tony Delroy Avatar answered Nov 12 '22 08:11

Tony Delroy