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



最近我对初始化感兴趣。我特别感兴趣的一件事是std::可选,因为它能够在类型的实例被声明后初始化它。我试过阅读可选标题中的代码,但代码太"夸夸其谈"了,我无法理解。

std::optional是如何延迟堆栈上对象的初始化的?我假设它只是在堆栈上保留sizeof(<whichever_type(字节数,然后重新解释这些字节以初始化<其中ever_bytes>。但它是如何具体做到这一点的呢?它是如何实现的?我自己该如何实现?

Edit:为了澄清,我知道std::optional基本上有一个bool成员来跟踪对象是否初始化,还有另一个成员,它包含数据。

然而,我不明白的是,如何可选地手动草签某些内容。

它是如何销毁一个对象的?在旧的被破坏后,它如何能够再次重建新的?

;明显的";表示std::optional<T>的方法是使用一个指示,该值是否与包含Tunion一起设置,即类似于以下内容:

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";
}   
}   

最新更新