Sunday, April 3, 2022

[SOLVED] Unit test to check for `noexcept` property for a C++ method

Issue

I have several methods that

  • have to be marked noexcept
  • must not be marked noexcept

How to write unit tests that check the method for being marked noexcept properly?

Reason: to ensure that in the future those properties are not changed during refactoring by other developers or an evil version of myself.

Currently, I use CMake/CTest and add hand-written executables to the test suite.


Solution

noexcept is also an operator. You can use it in a static assertion:

void foo() noexcept { }
void bar() { }

static_assert(noexcept(foo())); // OK
static_assert(noexcept(bar())); // Will fail

If it's a member function, then:

struct S {
    void foo() noexcept { }
};

static_assert(noexcept(S().foo()));

There's no function call or anything performed. The noexcept operator only checks the expression, it doesn't actually evaluate it.

To require that a function must not be noexcept, just use !noexcept(bar()).



Answered By - Nikos C.
Answer Checked By - Timothy Miller (WPSolving Admin)