In C++, = default and {} are not the same constructor

Hacker News by 3 min read 507x views
In C++, = default and {} are not the same constructor

Share Post

2 November 2026 · 3 min

You can compose an bare default constructor as span() = default or as span() {}. It can have notable effects on performance.

struct span {  const char *p;  int len;  const char *end;  span() = default; // or span() {}  span(const char *s, int n) : p(s), len(n), end(s + n) {} }; 

The constructor span() = default on its archetypal declaration makes extend trivial. The constructor span() {} is user-provided, so extend is not trivial.

Constructor Declaration What happens Members
span() = default span s; nothing uninitialized
span() = default span s{} the entire entity is zeroed, padding included; the constructor does not run zero
span() {} span s; the bare constructor is called; the compiler can delete the call uninitialized
span() {} span s{} the bare constructor is called; the entity is not zeroed uninitialized

An example

This extend is a commencement pointer, a length, and an end pointer. A box holds one span. The expression box() value-initializes that span. The iteration assigns a value-initialized box whenever i reaches n, and alternatively a extend of dimension i + 1:

struct box {  span s;  box() : s() {}  box(span in) : s(in) {} }; void consume(box &); void walk(const char *s, int n) {  for (int i = 0;; i++) {  box b;  b = i == n ? box() : box(span(s, i + 1));  if (i == n) { return; }  consume(b);  } } 

The box() way runs once, as the iteration exits, and that extend is not passed to consume.

With span() {}, GCC 16 (-O2 -march=x86-64) writes the three sectors immediately anywhere consume expects them:

.L4:  mov eax, ebx  mov QWORD PTR [rsp+16], rbx  mov rdi, rsp  add rbx, 1  sub eax, ebp  mov QWORD PTR [rsp], rbp  mov DWORD PTR [rsp+8], eax  call consume(box&)  cmp rbx, r12  jne .L4 

With span() = default, GCC 16 stores the end pointer, rbx, direct into the box. The commencement pointer and the dimension go through a temporary, and the archetypal 16 bytes of that impermanent are copied back.

.L3:  mov eax, ebx  mov QWORD PTR [rsp+32], rbp  mov rdi, rsp  sub eax, ebp  mov QWORD PTR [rsp+16], rbx  add rbx, 1  mov DWORD PTR [rsp+40], eax  movdqa xmm0, XMMWORD PTR [rsp+32]  movaps XMMWORD PTR [rsp], xmm0  call consume(box&)  cmp rbx, r12  jne .L3 

I period the finest of five runs of 100 myriad spans, on one center of an Intel Xeon Gold 6548N (Emerald Rapids), alongside -O2 -march=x86-64. My code is available.

compiler span() = default span() {}
GCC 14.3 1.73 ns/span 1.74 ns/span
GCC 15.2 7.75 ns/span 1.73 ns/span
GCC 16.2 8.04 ns/span 1.73 ns/span
clang 21 1.75 ns/span 1.74 ns/span

GCC 15 and GCC 16 obtain concerning 8 ns per extend alongside span() = default. The braces constructor stays near 1.7 ns.

With GCC 15 and GCC 16, the = default type is complete four times slower.

Other Article Hacker News
↑
Close Right Ads
Close Left Ads