In the previous post, we looked at the std::is_destructible<T> type trait. Today, let us try to understand another type trait std::is_empty<T>.
As per the specification, is_empty<T>::value will return true in the following cases:
– The class/struct has no non-static data member
– The class/struct does not define a virtual function
– The class/struct does not derive from a virtual base class
– The class/struct does not derive from non-empty base classes
Let us understand this concept by looking at some examples.
Here is our first example:
For convenience, we will use std::is_empty_v<T> instead of is_empty<T>::value. Also, just to make it a bit more interesting, I am printing the “sizeof” each class.
When we run this program, we get the following output:
The output is along the expected lines. You can see that even if a class is empty, its size is always greater than zero (the actual value is implementation dependent). The reason why class E is not empty is because it has an instance variable (although the class A is empty).
Let us now look at some examples involving inheritance.
Here is the corresponding output:
The behaviors of classes A, B, C, and D are as expected. However, I am surprised by the output corresponding to class E. I think this should be true since, as per the spec, deriving non-virtually from empty classes makes the class empty. I believe this is a bug in Microsoft C++ compiler.
Here are some more examples involving inheritance:
These involve virtual functions and virtual derivation. What do we expect in these cases?
Again, there is no surprise here. If a class has a virtual function and/or derives virtually from another class, it is not an empty class as per the spec.
Before concluding, let us consider the case of a union and a class with bit field:
This is the output generated:
As expected, unions are non-empty. And, a class with a bit field of size zero is considered empty.
I hope the above examples provide some clarity on the behavior of std::is_empty<T> type trait.
For the examples, I used Microsoft Visual Studio 2019 (ver 16.4.5). You can download the examples from here.
Have a nice weekend!
Recent Comments