Search code examples
c++exceptionc++11nothrow

How to specify nothrow exception specifier for destructor?


I am trying to specify that a function is nothrow whenever the destructor of Foo doesn't throw. I can do this by using the type trait std::is_nothrow_destructible<>. How can I do this directly? I've tried the following, but it doesn't compile if I uncomment the commented line

#include <iostream>
#include <type_traits>

class Foo
{
public:
    ~Foo() noexcept {}
};

// void f() noexcept(noexcept(~Foo{})) { } // error here
void g() noexcept(std::is_nothrow_destructible<Foo>::value) 
{

}

int main()
{
    g();
}

I get an error

 error: no match for 'operator~' (operand type is 'Foo')

The error specifier noexcept(noexcept(~Foo())) is not OK, although for constructors I can use noexcept(noexcept(Foo())). Am I missing some obvious syntax here?


Solution

  • Destructors can only be called through a member access expression. So the syntax would be:

    void f() noexcept(noexcept(std::declval<Foo>().~Foo()))