Modern C++ › C++20
consteval, jthread and Other Additions
Immediate functions, cooperative cancellation and designated initializers.
Explanation
A tour of the smaller C++20 additions you will use most.
consteval: an immediate function. Every call must be evaluated at compile time, or the program is ill-formed. It guarantees what constexpr only permits.
constinit: requires a variable with static/thread storage to be initialized at compile time (preventing the static-initialization-order problem) while staying mutable.
std::jthread: a thread that joins automatically in its destructor and supports cooperative cancellation via std::stop_token; request_stop() signals it.
Designated initializers: Point{.x = 1, .y = 2} for aggregates, in declaration order.
Other handy items:
| Feature | Header | Use |
|---|---|---|
std::latch, std::barrier |
<latch>, <barrier> |
one-shot / reusable thread synchronization points |
std::counting_semaphore |
<semaphore> |
limit concurrent access |
std::source_location |
<source_location> |
file/line/function without macros |
std::numbers::pi, e, sqrt2 |
<numbers> |
math constants |
contains() |
map, set |
membership test |
starts_with(), ends_with() |
string, string_view |
prefix/suffix tests |
std::erase, std::erase_if |
containers | one-call erase-remove |
std::bit_cast, std::popcount |
<bit> |
safe type punning, bit counting |
[[likely]], [[unlikely]] |
branch hints |
Example
#include <bit>
#include <chrono>
#include <iostream>
#include <latch>
#include <map>
#include <numbers>
#include <source_location>
#include <string>
#include <thread>
#include <vector>
consteval int cube(int x) { return x * x * x; } // must run at compile time
constinit int counter = cube(3); // initialized at compile time, mutable
struct Config { int width; int height; bool fullscreen; };
void log(const std::string& msg, std::source_location loc = std::source_location::current()) {
std::cout << loc.function_name() << ":" << loc.line() << " " << msg << "\n";
}
int main() {
constexpr int c = cube(4); // 64
// int n = 5; cube(n); // error: not a constant expression
++counter;
std::cout << c << " " << counter << "\n";
Config cfg{.width = 800, .height = 600}; // designated initializers; fullscreen = false
std::cout << cfg.width << "x" << cfg.height << " " << cfg.fullscreen << "\n";
std::jthread worker([](std::stop_token st) { // stop token is passed automatically
int ticks = 0;
while (!st.stop_requested()) {
++ticks;
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
std::cout << "worker stopped after ticks > 0: " << (ticks > 0) << "\n";
});
std::this_thread::sleep_for(std::chrono::milliseconds(30));
worker.request_stop(); // jthread joins in its destructor
std::latch done(2); // wait for 2 events
std::jthread t1([&] { done.count_down(); });
std::jthread t2([&] { done.count_down(); });
done.wait();
std::cout << "both finished\n";
std::map<std::string, int> m{{"a", 1}};
std::string path = "/usr/local/bin";
std::cout << m.contains("a") << path.starts_with("/usr") << path.ends_with("sbin") << "\n"; // 110
std::vector<int> v{1, 2, 3, 4, 5, 6};
std::erase_if(v, [](int x) { return x % 2 == 0; }); // replaces erase-remove
std::cout << v.size() << " " << std::popcount(0b1011u) << " "
<< std::numbers::pi_v<double> << "\n"; // 3 3 3.14159
log("done");
return 0;
}
Common pitfalls
constevalfunctions can’t be used with runtime values; useconstexprif you also need run-time calls.constinitdoesn’t make the variableconst; it only forces compile-time initialization.- A
jthreadlambda taking astop_tokenas its first parameter gets one automatically; forgetting to check it in the loop meansrequest_stop()does nothing. std::barrier/latchcount mistakes deadlock: a latch waits forever if the count never reaches zero.- Designated initializers must follow declaration order in C++ (unlike C), and can’t be mixed with positional ones.
std::erase(free function) is for containers;std::mapuseserase_iftoo, but only the free-function versions are new.
Legacy vs modern
// C++11/17: manual join, flag for cancellation
std::atomic<bool> stop{false};
std::thread t(worker, std::ref(stop)); ... stop = true; t.join(); // forget join -> terminate()
// C++20
std::jthread t(worker); // auto-joins; t.request_stop();
__FILE__/__LINE__ macros become std::source_location; the erase-remove idiom from Algorithms becomes std::erase_if. See also Threads, Mutexes and Atomics.
Exercises
1. What is the difference between constexpr and consteval for a function?
A constexpr function may be evaluated at compile time but can also run at run time. A consteval function must be evaluated at compile time (every call is a constant expression).