C++ 中的向量持久性和瞬态性

vector persistent and transient in C++

有人可以帮助我理解这段代码吗?

transient()persistent() 在这里做什么?

参考:
CppCon 2017:Juan Pedro Bolivar Puente,“后现代不可变数据结构”

时间戳:
19:03

vector<int> myitoa(vector<int> v, int first, int last)
{
    auto t = v.transient();
    for (auto i = first; i < last; ++i)
        t.push_back(i);
    return t.persistent();
}

See the video here

另外,我编译的时候报错了:

'class std::vector' has no member named 'transient'

需要任何特定的头文件吗?

vector 在这种情况下不是 std::vector,它没有 transient()persistent() 方法,如编译器错误状态。正如 Juan 在 18:06:

中所述,它实际上是一个 immer::vector

So, I'm using the immer namespace everywhere here. Nothing is std vector. This is an immutable vector ...

如果你仔细听视频,Juan 会解释 transient()persistent() 实际上在做什么,以及为什么 (19:00 - 25:58)。

简而言之,vector 是不可变的,其内容无法修改,因此transient()vector 进行复制+写入视图。当循环修改瞬态时,会生成 vector 数据的新副本,循环可以根据需要自由修改。然后 persistent() 从瞬态数据中创建一个新的不可变 vector

这在 Transient Data Structures:

上有更详细的介绍

Transient data structures are always created from an existing persistent ... data structure...

You obtain a transient 'copy' of a data structure by calling transient. This creates a new transient data structure that is a copy of the source, and has the same performance characteristics. In fact, it mostly is the source data structure, and highlights the first feature of transients - creating one is O(1). It shares structure with its source, just as persistent copies share structure.

The second feature of transients is that creating one does not modify the source, and the source cannot be modified via use of the transient. Your source data is immutable and persistent as always.

...

When you are finished building up your results, you can create a persistent data structure by calling persistent! on the transient. This operation is also O(1). Subsequent to calling persistent!, the transient should not be used, and all operations will throw exceptions. This will be true also for any aliases you might have created.