Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`is_trivially_destructible` does not work with inherited class

#include <iostream>
using namespace std;


    class NoConstructOperation
    {
    protected:
        NoConstructOperation() = default;
        virtual ~NoConstructOperation() = default;
    public:
        NoConstructOperation(const NoConstructOperation&) = delete;
        NoConstructOperation& operator =(NoConstructOperation&) = delete;
        NoConstructOperation(NoConstructOperation&&) = delete;
        NoConstructOperation& operator = (NoConstructOperation&&) = delete;
    };

class Myclass:public NoConstructOperation
{

};


int main() {
    static_assert(!std::is_trivially_destructible<Myclass>::value, "Compiler provided destructor is public: Please declare it private");
    return 0;
}  

If I do not inherit Myclass with NoConstructOperation above code gives compilation error with static assert.
But if I inherit Myclass with NoConstructOperation is_trivially_destructible check does not work, even though Myclass constructor is public. This code compiles , what is the reason?

like image 608
gaurav bharadwaj Avatar asked Jan 06 '23 08:01

gaurav bharadwaj


1 Answers

You're defining NoConstructorOperation's destructor as virtual. Removing virtual will trigger the static assertion as intended: wandbox example.

From cplusplus.com:

A trivially destructible class is a class (defined with class, struct or union) that:

  • uses the implicitly defined destructor.

  • the destructor is not virtual.

  • its base class and non-static data members (if any) are themselves also trivially destructible types.

From standard draft N4567 $12.4:

A destructor is trivial if it is not user-provided and if:

(5.4) — the destructor is not virtual,

(5.5) — all of the direct base classes of its class have trivial destructors, and

(5.6) — for all of the non-static data members of its class that are of class type (or array thereof), each such class has a trivial destructor.

like image 79
Vittorio Romeo Avatar answered Jan 13 '23 17:01

Vittorio Romeo