C++
Module 25: Type System and Advanced Language FeaturesAdvanced55 min read

constexpr, consteval, Value Categories (lvalue/rvalue), Move Semantics & Perfect Forwarding

Master compile-time evaluation (constexpr, consteval, static_assert), type_traits, lvalues/xvalues/prvalues, std::move, and std::forward.

Key Takeaways & Core Concepts
  • `constexpr`: Can evaluate at compile time or runtime.
  • `consteval`: Must evaluate at compile time (immediate function).
  • `constinit`: Guarantees compile-time static initialization (no static initialization order fiasco).
  • `<type_traits>` + `static_assert`: Query and enforce type properties at compile time (std::is_integral_v<T>).

1. `const`, `constexpr`, `consteval` (C++20), `constinit` (C++20) & `type_traits`

  • `constexpr`: Can evaluate at compile time or runtime.
  • `consteval`: Must evaluate at compile time (immediate function).
  • `constinit`: Guarantees compile-time static initialization (no static initialization order fiasco).
  • `<type_traits>` + `static_assert`: Query and enforce type properties at compile time (std::is_integral_v<T>).
1. Move Semantics & Perfect Forwarding
1#include <iostream>
2#include <string>
3#include <utility>
4
5void consume(const std::string& s) { std::cout << "Lvalue: " << s << "\n"; }
6void consume(std::string&& s) { std::cout << "Rvalue moved: " << s << "\n"; }
7
8template <typename T>
9void relay(T&& arg) { consume(std::forward<T>(arg)); }
10
11int main() {
12 std::string msg = "CodeZov";
13 relay(msg);
14 relay(std::move(msg));
15 return 0;
16}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
16 lines
Note: `std::forward<T>` preserves lvalue vs rvalue category across template forwarding.

2. Value Categories: lvalue, prvalue, xvalue

  • lvalue: Has identity & address (int x = 5;).
  • prvalue: Pure rvalue temporary (5, x + 1).
  • xvalue: Expiring value (std::move(x)).

3. Move Semantics (`std::move`) & Perfect Forwarding (`std::forward`)

std::move(obj) casts to T&& so the move constructor transfers heap pointers in O(1). std::forward<T>(arg) in forwarding references (T&& in deduced template context) preserves lvalue/rvalue-ness.

Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)