Skip to content

libc++: std::nested_exception::nested_ptr() is null or possibly indeterminate with Homebrew g++ on the Mac #113036

@alf-p-steinbach

Description

@alf-p-steinbach

The following code works fine, as expected, with clang++, but reports nullpointer with Homebrew g++.

#include <exception>
#include <iostream>
#include <stdexcept>
using namespace std;

#include <stdlib.h>         // exit, EXIT_...

void throw_nested()
{
    try {
        throw runtime_error( "First exception" );
    } catch( ... ) {
        throw_with_nested( runtime_error( "Second exception" ) );
    }
}

void check( const exception& x )
{
    cout << "Checking...\n";
    try {
        //! rethrow_if_nested( x );     -- "libc++abi: terminating"
        if( const auto p_nest = dynamic_cast<const nested_exception*>( &x ) ) {
            cout << "Internal rethrowing...\n";
            //! p_nest->rethrow_nested();       -- "libc++abi: terminating"
            const auto x_ptr = p_nest->nested_ptr();
            if( not x_ptr ) {
                cout << "!Nested exception pointer is null.\n";
                exit( EXIT_FAILURE );           //! libc++
            }
            rethrow_exception( x_ptr );
        }
        cout << "Not nested.\n";
    } catch( ... ) {
        cout << "Nested!\n";
    }
    cout << "Done.\n";
}

auto main() -> int
{
    try {
        throw_nested();
    } catch( const exception& x ) {
        check( x );
    }
}

Results:

$ echo $OPT
-std=c++17 -pedantic-errors -Wall -Wextra

[/Users/alf/f/source/compiler-bugs]
$ clang++ ${=OPT} throw_if_nested.cpp -oa

[/Users/alf/f/source/compiler-bugs]
$ ./a
Checking...
Internal rethrowing...
Nested!
Done.

[/Users/alf/f/source/compiler-bugs]
$ g++ ${=OPT} throw_if_nested.cpp -ob

[/Users/alf/f/source/compiler-bugs]
$ ./b
Checking...
Internal rethrowing...
!Nested exception pointer is null.

Compiler versions:

  • Apple clang version 16.0.0 (clang-1600.0.26.3) / Target: arm64-apple-darwin24.0.0
  • g++-14 (Homebrew GCC 14.2.0) 14.2.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    libc++libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions