← Wed, Nov 25 digest

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

read article ↗ hn thread ↗

In C++, using = default versus an empty body for a default constructor changes type triviality, causing GCC to generate significantly slower initialization code.

summary is enough The blog post cleanly demonstrates a surprising performance trap, though the underlying mechanism stems from standard C++ triviality rules.

summary

Daniel Lemire highlights that defining a default constructor as = default versus {} alters whether a struct is treated as trivial by the compiler. In a microbenchmark with GCC 16, the trivial version compiled with = default resulted in extra temporary copying, making it over four times slower than the non-trivial {} version. Commenters note that while this is a real footgun, real-world impact depends heavily on member initializers.

key points

  1. span() = default makes a type trivial, while span() {} is user-provided and non-trivial.
  2. Under GCC 16, the trivial constructor version triggered extra temporary variable copying, making a benchmark loop over four times slower.
  3. Commenters point out that explicitly member-initializing fields largely mitigates this difference in practical code.

who should read it

C++ developers interested in compiler code generation, performance nuances, and object triviality.

discussion skeptical

consensus

Commenters use the post to lament C++'s notorious complexity and debate the necessity of complex constructor rules compared to languages like Rust or Go.

pushback

Some argue the example is contrived because real-world structs typically use default member initializers.

best comment by spacechild1 ↗

The example is pretty contrived because in practice you'd want to zero-initialize the members in the default constructor anyway.

struct span { const char *p = nullptr; size_t len = 0; span() = default; // or span() {} span(const char *s, size_t n) : p(s), len(n) {} };

In that case, there is no difference between

span s;

and

span s{};

There are only few use cases where you want a default constructor that does not initialize its members. One example are wrappers around primitive types where you want to closely preserve the original semantics. Whether that's a good idea in the first place …

It shows how default member initializers eliminate the performance difference in practice.

Generated by an LLM from the article and thread. Check the sources before relying on it.