std::optional 延迟初始化如何? / std::optional 是如何实现的?

问题描述

最近我对初始化产生了兴趣。我特别感兴趣的一件事是 std::optional ,因为它能够在声明类型后初始化一个类型的实例。我曾尝试阅读可选标头中的代码,但代码太“夸张”了,我无法理解。

std::optional 如何延迟栈上对象的初始化?我假设它只是在堆栈上保留 sizeof( 的初始化重新解释这些字节。但它具体是如何做到的呢?它是如何实施的?我该如何自己实现?

编辑:澄清一下,我知道 std::optional 基本上有一个 bool 成员来跟踪对象是否已初始化,以及另一个包含数据的成员。

然而,我不明白的是 optional 是如何能够手动初始化某些东西的。

它如何能够破坏一个对象?旧的被破坏后如何​​重新构建新的?

解决方法

表示 std::optional<T> 的“明显”方式是使用指示值是否与包含 unionT 一起设置,即,如下所示:>

template <typename T>
class optional {
    bool isSet = false;
    union { T value; };
public:
    // ...
};

默认情况下,union 中的成员未初始化。相反,您需要使用放置 new 和手动销毁来管理 union 中实体的生命周期。从概念上讲,这类似于使用字节数组,但编译器会处理任何对齐要求。

这是一个显示了一些操作的程序:

#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <cassert>

template <typename T>
class optional {
    bool isSet = false;
    union { T value; };
    void destroy() { if (this->isSet) { this->isSet = true; this->value.~T(); } }

public:
    optional() {}
    ~optional() { this->destroy(); }
    optional& operator=(T&& v) {
        this->destroy();
        new(&this->value) T(std::move(v));
        this->isSet = true;
        return *this;
    }   

    explicit operator bool() const { return this->isSet; }
    T&       operator*()       { assert(this->isSet); return this->value; }
    T const& operator*() const { assert(this->isSet); return this->value; }
};  

int main()
{   
    optional<std::string> o,p;
    o = "hello";
    if (o) {
        std::cout << "optional='" << *o << "'\n";
    }   
}