I don't understand why would I ever do this:
struct S {
int a;
S(int aa) : a(aa) {}
S() = default;
};
Why not just say:
S() {} // instead of S() = default;
why bring in a new syntax for that?
I don't understand why would I ever do this:
struct S {
int a;
S(int aa) : a(aa) {}
S() = default;
};
Why not just say:
S() {} // instead of S() = default;
why bring in a new syntax for that?
I have an example that will show the difference:
#include <iostream>
using namespace std;
class A
{
public:
int x;
A(){}
};
class B
{
public:
int x;
B()=default;
};
int main()
{
int x = 5;
new(&x)A(); // Call for empty constructor, which does nothing
cout << x << endl;
new(&x)B; // Call for default constructor
cout << x << endl;
new(&x)B(); // Call for default constructor + Value initialization
cout << x << endl;
return 0;
}
Output:
5
5
0
As we can see the call for empty A() constructor does not initialize the members, while B() does it.
Due to the deprecation of std::is_pod and its alternative std::is_trivial && std::is_standard_layout, the snippet from @JosephMansfield 's answer becomes:
#include <type_traits>
struct X {
X() = default;
};
struct Y {
Y() {}
};
int main() {
static_assert(std::is_trivial_v<X>, "X should be trivial");
static_assert(std::is_standard_layout_v<X>, "X should be standard layout");
static_assert(!std::is_trivial_v<Y>, "Y should not be trivial");
static_assert(std::is_standard_layout_v<Y>, "Y should be standard layout");
}
Note that the Y is still of standard layout.
There is a signicant difference when creating an object via new T(). In case of defaulted constructor aggregate initialization will take place, initializing all member values to default values. This will not happen in case of empty constructor. (won't happen with new T either)
Consider the following class:
struct T {
T() = default;
T(int x, int c) : s(c) {
for (int i = 0; i < s; i++) {
d[i] = x;
}
}
T(const T& o) {
s = o.s;
for (int i = 0; i < s; i++) {
d[i] = o.d[i];
}
}
void push(int x) { d[s++] = x; }
int pop() { return d[--s]; }
private:
int s = 0;
int d[1<<20];
};
new T() will initialize all members to zero, including the 4 MiB array (memset to 0 in case of gcc). This is obviously not desired in this case, defining an empty constructor T() {} would prevent that.
In fact I tripped on such case once, when CLion suggested to replace T() {} with T() = default. It resulted in significant performance drop and hours of debugging/benchmarking.
So I prefer to use an empty constructor after all, unless I really want to be able to use aggregate initialization.