---
title: 'Memory allocation in std::optional'
url: 'http://www.samansaadi.com/fa/blog/std_optional'
markdown: 'http://www.samansaadi.com/fa/blog/std_optional.md'
lang: en
date: '2021-06-12'
description: 'C++17 introduces std::optional. Before C++17 we could use Boost.Optional. The question is when we should use smart pointers and when to use std::optional? Memory allocation For smart pointers we have'
taxonomy:
  category:
    - en_blog
  en_tag:
    - C++
    - programming
    - 'memory management'
  archives_month:
    - jun_2021
  archives_year:
    - '2021'
---

# Memory allocation in std::optional

[ خانه ](http://www.samansaadi.com/fa)     [ وبلاگ ](http://www.samansaadi.com/fa/blog)      Memory allocation in std::optional    

C++17 introduces `std::optional`. Before C++17 we could use `Boost.Optional`. The question is when we should use smart pointers and when to use `std::optional`?

## Memory allocation

For smart pointers we have a lot of choices: `std:unique_ptr`, `std::shared_ptr` and `std::weak_ptr`. This [website](https://www.nextptr.com/tutorial/ta1450413058/unique_ptr-shared_ptr-weak_ptr-or-reference_wrapper-for-class-relationships) explains the differences and when to use them.

I'm going to focus on memory allocation differences between `std::optional` and smart pointers. According to [cppreference](https://en.cppreference.com/w/cpp/utility/optional):

> Any instance of optional at any given point in time either contains a value or does not contain a value. If an optional contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though operator\*() and operator->() are defined.

There are two implications here:

1. when `std::optional` is created, the memory is allocated for `T`. Unlike smart pointers, [lazy initialization](https://en.wikipedia.org/wiki/Lazy_initialization) is not possible
2. `T` may not have default constructor. So `std::optional` must handle this situation

Based on these facts when lazy initialization is important (e.g. the size of `T` is huge or most of the time `std::optional` doesn't have a value), it's better to use smart pointers; otherwise use `std::optional`. For more information read this [answer](https://stackoverflow.com/a/44856779).

## High-level implementation details

The second implication is a little tricky. I've looked at `libstdc++` and I've noticed they address it by using [Unions](https://en.cppreference.com/w/cpp/language/union):

> The union is only as big as necessary to hold its largest data member. The other data members are allocated in the same bytes as part of that largest member. The details of that allocation are implementation-defined but all non-static data members will have the same address (since C++14). It's undefined behavior to read from the member of the union that wasn't most recently written. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union.

I wrote a simplified example that shows the idea behind it:

```
#include <iostream>
#include <cstdint>

struct Data
{
  Data(std::int64_t data_) : data(data_) {}
  std::int64_t data;
};

struct EmptyByte { };

union Storage
{
  Storage() : zeroByte()
  {
    std::cout << "zeroByte is initialized" << std::endl;
  }

  Storage(std::int64_t data_) : data(data_)
  {
    std::cout << "data is initialized" << std::endl;
  }

  EmptyByte zeroByte;
  Data data;
};

int main()
{
  std::cout << "Data size: " << sizeof(Data) << std::endl;            // Data size: 8
  std::cout << "EmptyByte size: " << sizeof(EmptyByte) << std::endl;  // EmptyByte size: 1
  std::cout << "Storage size: " << sizeof(Storage) << std::endl;      // Storage Size: 8

  Storage s1;     // zeroByte is initialized
  Storage s2(7);  // data is initialized
}
```

As you can see `Data` doesn't have a default constructor but `Storage` union takes care of it. So `union` addresses the second implication.

For addressing the first implication, `std::optional` is using a technique named [placement new](https://en.cppreference.com/w/cpp/language/new) to use a pre-allocated memory:

```
// within any block scope...
{
    alignas(T) unsigned char buf[sizeof(T)];
    // Statically allocate the storage with automatic storage duration
    // which is large enough for any object of type `T`.
    T* tptr = new(buf) T; // Construct a `T` object, placing it directly into your 
                          // pre-allocated storage at memory address `buf`.
    tptr->~T();           // You must **manually** call the object's destructor
                          // if its side effects is depended by the program.
}                         // Leaving this block scope automatically deallocates `buf`.
```

As you can see the implementation details are elegant and easy to understand.

  پست قبلی پست بعدی

#### مقاله‌ی تصادفی

 [ خوش‌شانس هستم!](http://www.samansaadi.com/fa/blog/random)

#### لینک‌های مفید

- [فونت‌های فارسی وب](http://persian-computing.org/download/farsifonts-0.4.zip)
- [پشتیبانی از صفحه‌کلید استاندارد فارسی (ISIRI 9147) در ویندوز](http://persian-computing.org/download/Iranian_Standard_Persian_Keyboard_(ISIRI_9147)_(Version_2.0).zip)
- [صفحه‌کلید فارسی در ویکی‌پدیا](https://fa.wikipedia.org/wiki/%D9%88%DB%8C%DA%A9%DB%8C%E2%80%8C%D9%BE%D8%AF%DB%8C%D8%A7:%D8%B5%D9%81%D8%AD%D9%87%E2%80%8C%DA%A9%D9%84%DB%8C%D8%AF_%D9%81%D8%A7%D8%B1%D8%B3%DB%8C)
- [محاسبات فارسی](http://persian-computing.org/)
- [گروه محاسبات فارسی](https://groups.google.com/forum/?hl=fa#!forum/persian-computing-fa)
- [راهنمای پایه‌ی ++C](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md)
- [هکر رنک](https://www.hackerrank.com/)
- [معماری نرم‌افزارهای منبع باز](https://aosabook.org/en/index.html)

#### تگ‌های معروف

  [فونت](http://www.samansaadi.com/fa/blog/fa_tag:%D9%81%D9%88%D9%86%D8%AA) [چیدمان صفحه‌کلید](http://www.samansaadi.com/fa/blog/fa_tag:%DA%86%DB%8C%D8%AF%D9%85%D8%A7%D9%86%20%D8%B5%D9%81%D8%AD%D9%87%E2%80%8C%DA%A9%D9%84%DB%8C%D8%AF) 

#### آرشیو

- [ 1 June 2020  ](http://www.samansaadi.com/fa/blog/archives_month:jun_2020)

#### فیدها

 [ Atom 1.0](http://www.samansaadi.com/fa/blog.atom) [ RSS](http://www.samansaadi.com/fa/blog.rss)

---

## Navigation

- Parent: [وبلاگ](http://www.samansaadi.com/fa/blog.md)
- Previous: [Emails or Messaging Apps?](http://www.samansaadi.com/fa/blog/secure_communication.md)
- Next: [Time Zones](http://www.samansaadi.com/fa/blog/time_zones.md)
