mercredi 11 août 2021

"Thrown exception type is not nothrow copy constructible" simply using std::runtime_error in constructor

Here is the constructor of my class, very simple.

MyClass::MyClass()
{
  throw std::runtime_error("timeout.");
}

The line has a Clang-tidy warning Clang-Tidy: Thrown exception type is not nothrow copy constructible.

From ERR60-CPP. Exception objects must be nothrow copy constructible,

#include <stdexcept>
#include <type_traits>
 
struct S : std::runtime_error {
  S(const char *msg) : std::runtime_error(msg) {}
};
  
static_assert(std::is_nothrow_copy_constructible<S>::value,
              "S must be nothrow copy constructible");
 
void g() {
  // If some condition doesn't hold...
  throw S("Condition did not hold");
}
 
void f() {
  try {
    g();
  } catch (S &s) {
    // Handle error
  }
}

I get this warning at the static_assert:

Static_assert failed due to requirement 'std::is_nothrow_copy_constructible::value' "S must be nothrow copy constructible

screenshot

  • I still didn't get why I get the ERR60-CPP warning... I'm simply using directly std::runtime_error as my exception type.
  • Since noexcept(false) is by default, I don't put it in the constructor's definition.

Source: Handling "Thrown exception type is not nothrow copy constructible" Warning

Aucun commentaire:

Enregistrer un commentaire