Quick Q: std::rethrow_exception and thrown exception type

Quick A: std::make_exception_ptr creates a reference on a copy.

Recently on SO:

std::rethrow_exception and thrown exception type

From documentation for std::make_exception_ptr:

Creates an std::exception_ptr that holds a reference to a copy of e.

Unfortunately, copying e means you get object slicing (which @Mohamad Elghawi points out is also more prominently mentioned later on that page). When you call std::make_exception_ptr<RecognitionException>, it will hold a copy of a RecognitionException, not any derived class.

But you don't need exception_ptr at all here. Even though reportError does not have the try...catch in scope, you can still use throw; to re-throw the current exception.

#include <stdio.h>

struct A { virtual ~A() = default; };
struct B : A { };

void reportError() {
  try {
    throw;
  }
  catch (B &) {
    puts("caught B");
  }
  catch (A &) {
    puts("caught A");
  }
}

int main() {
  try {
    throw B();
  }
  catch (A &) {
    reportError();
  }
}

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.