c++default-constructoreffective-c++empty-class

What function does C++ write and call in an empty class?


In the book Effective C++, I saw the passage below:

As a result, if you write

class Empty{};

it's essentially the same as if you'd written this:

class Empty {
public:
    Empty() { ... }
    Empty(const Empty& rhs) { ... }
    ~Empty() { ... }
    Empty& operator=(const Empty& rhs) { ... } // copy assignment operator
};

The following code will cause each function to be generated:

Empty e1;
Empty e2(e1);
e2 = e1;

But after disassembling the executable file which was created by compiling the code above, I realized it not the case: there isn't any function being invoked.

Here is the major assembly code:

00000000004006cd <main>:
  4006cd:       55                      push   %rbp
  4006ce:       48 89 e5                mov    %rsp,%rbp
  4006d1:       b8 00 00 00 00          mov    $0x0,%eax
  4006d6:       5d                      pop    %rbp
  4006d7:       c3                      retq 

There isn't any function named "Empty" in the .text segment.

Then what indeed is the behaviour of a compiler after we call a constructor or assignment of an empty class? Does it generate some functions as the book said? If so, where are they stored?


Solution

  • The functions exist, but can be inlined.

    When the compiler inlines the functions, it realizes they are no-ops, and there is no code generated.

    What the book is saying, is true to an extent, the notional functions are created by the compiler, for inline and direct calling.

    But the generated code is empty, so an optimizing compiler will then remove any evidence of the function (setting up a this pointer), and the functions will never be directly called.

    The book is not really trying to explain the code generated, but the impact of creating a class, and the "hidden" functions it generates for normal operation.