Skip to content

Instantly share code, notes, and snippets.

@zhiguangwang
Created September 29, 2017 04:19
Show Gist options
  • Save zhiguangwang/52d0c62b21042fe86ee31bdd363cdbe6 to your computer and use it in GitHub Desktop.
Save zhiguangwang/52d0c62b21042fe86ee31bdd363cdbe6 to your computer and use it in GitHub Desktop.
sizeof std::optional<T>
#include <iostream>
#include <string>
#include <optional>
int main()
{
std::cout << "sizeof bool is " << sizeof(bool) << '\n';
std::cout << "sizeof std::optional<bool> is " << sizeof(std::optional<bool>) << "\n\n";
std::cout << "sizeof short is " << sizeof(short) << '\n';
std::cout << "sizeof std::optional<short> is " << sizeof(std::optional<short>) << "\n\n";
std::cout << "sizeof int is " << sizeof(int) << '\n';
std::cout << "sizeof std::optional<int> is " << sizeof(std::optional<int>) << "\n\n";
std::cout << "sizeof int64_t is " << sizeof(int64_t) << '\n';
std::cout << "sizeof std::optional<int64_t> is " << sizeof(std::optional<int64_t>) << "\n\n";
std::cout << "sizeof void* is " << sizeof(void*) << '\n';
std::cout << "sizeof std::optional<void*> is " << sizeof(std::optional<void*>) << "\n\n";
std::cout << "sizeof std::string is " << sizeof(std::string) << '\n';
std::cout << "sizeof std::optional<std::string> is " << sizeof(std::optional<std::string>) << "\n\n";
}

On GCC 7.2:

sizeof bool is 1
sizeof std::optional<bool> is 2

sizeof short is 2
sizeof std::optional<short> is 4

sizeof int is 4
sizeof std::optional<int> is 8

sizeof int64_t is 8
sizeof std::optional<int64_t> is 16

sizeof void* is 8
sizeof std::optional<void*> is 16

sizeof std::string is 32
sizeof std::optional<std::string> is 40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment