The lifetime of an abandoned object caught by the link

C ++ Standard, clause 15.1.4. sais:

The memory for the temporary copy of the generated exception is allocated in an undefined manner, with the exception of the cases specified in clause 3.7.3.1. Temporary storage is maintained until a handler is executed for this exception.

I am wondering why this code crashes (I know this is not the best practice):

class magicException
{
private:
    char* m_message;

public:
    magicException(const char* message)
    {
        m_message = new char[strlen(message) + 1];
        strcpy(m_message, message);
    }

    ~magicException()
    {
        cout << "Destructor called." << endl;
        delete[] m_message;
    }

    char* getMessage()
    {
        return m_message;
    }
};

void someFunction()
{
    throw magicException("Bang!");
}

int main(int argc, char * argv[])
{
    try
    {
        someFunction();
    }
    catch (magicException& ex)
    {
        cout << ex.getMessage() << endl;
    }

    return 0;
}

In particular, the destructor of the thrown magicException object is called before the catch block. If I, however, add a copy constructor to my class:

magicException(const magicException& other)
{
    cout << "Copy constructor called." << endl;
    m_message = new char[strlen(other.m_message) + 1];
    strcpy(m_message, other.m_message);
}

, ( catch), , - . (Visual ++ 2008 ), - ?

+3
1

, magicException catch.

, , , () . . ++ ( ) , .

+4

Source: https://habr.com/ru/post/1729672/


All Articles