const

Facts

  • No data race - obviously, because it cannot be modified

  • Beware of const_cast<> though: modifying a variable after removing const is undefined behavior

  • Can be used in constexpr (but see constexpr)

  • Might be evaluated at compile time - no guarantee though ⟶ that is the point in constexpr

const Variables Might Disappear Entirely

#include <iostream>

const int answer = 42;

int main()
{
    std::cout << answer << '\n';
    return 0;
}
  • Optimization off ⟶ answer in rodata

$ g++ -O0 const-global-variable.cpp
$ nm --demangle a.out | grep answer
0000000000402010 r answer
  • -O3 (at least) ⟶ optimized out entirely

$ g++ -O3 const-global-variable.cpp
$ nm --demangle a.out | grep answer

const Might Generally Disappear: std::map<>?

#include <map>
#include <iostream>

const int key = 7;
const int value = 42;
const std::map<int, int> the_map{{key, value}};

int main()
{
    std::cout << the_map.at(key) << '\n';
    return 0;
}
$ g++ -O3 const-used-in-const-map.cpp
$ nm --demangle a.out | grep the_map
00000000004041a0 b the_map

const Might Generally Disappear: std::array<>?

std::array<> has a trivial destructor, so a compiler could optimize const objects out.

#include <array>
#include <iostream>

const int size = 7;
const std::array<int, size> the_array{2,3,4,5,6,7,8};

int main()
{
    std::cout << the_array.size() << '\n';
    return 0;
}
  • Does not disappear by default (GCC 13)

$ g++ const-used-in-const-array.cpp
$ nm --demangle a.out | grep the_array
0000000000402020 r the_array
  • Does disappear with -O3

$ g++ -O3 const-used-in-const-array.cpp
$ nm --demangle a.out | grep the_array