Home > Enterprise >  Do C compilers generate a def ctor if the class was not initialized?
Do C compilers generate a def ctor if the class was not initialized?

Time:10-27

I have written a utility class (acts as a helper class, I guess) that has only a few static member functions to be used in another class. It does not have any non-static members (variables or functions). So it also doesn't have any explicit ctors or dtor.

And the question is, does my compiler (GCC v11.2 and -std=c 20) still generate an implicit default ctor and a dtor for the utility class? If it does, then how should I prevent it from doing so? since I haven't initialized any instance of that class in my code.

CodePudding user response:

(I'm slightly side-stepping your question in lieu of providing unsolicited advice) If you have a collection of static functions and your class does not require any state

class Example
{
public:
    static void Foo();
    static int Bar();
};

then you should likely not be using a class in the first place, rather these should probably be free functions in a namespace

namespace Example
{
    void Foo();
    int Bar();
}

which still allows you to invoke them as Example::Foo() and Example::Bar() but now you don't have to worry about someone trying to instantiate your "class" since that's not what you intended to design it for.

CodePudding user response:

As is already mentioned, you should be using namespaces for this type of context. That being said, to answer your question, the answer is "not really". The compiler must "create" one, but it doesn't have to generate code for it.

I cannot find anything explicitly stating this in the standard, however, if you create a simple class which just has static functions, and view the generated assembly code, you can see that no constructor is created. Even if you attempt to instantiate the object, using either automatic or dynamic variables, no code is generated. Simply put, since there's nothing that a default constructor would even do, there's no reason for the compiler to generate any code.

You can view this here using gcc 11.2 with C 20 enable. Note that I have optimizations turned off, just to show that it's not the -O3 which removes the call.

  • Related