[英]C++ assign object value in uninitialized memory
I'm writing a B-Tree class for databases.我正在为数据库编写一个 B-Tree 类。
struct Node {
// invariant: t - 1 <= size <= 2 * t - 1
// invariant: capacity 2 * t - 1
K *keys_ = nullptr;
// invariant: t <= size <= 2 * t
// invariant: size of children_ is size of keys_ + 1
// invariant: capacity 2 * t
std::array<std::unique_ptr<Node>, 2 * t> children_;
// number of stored keys
// invariant: except root, the number of keys is at least t - 1, at most 2 * t - 1
// invariant: except root, for non-leaf nodes, the number of children is at least t, at most 2 * t
// invariant: child_0 <= key_0 <= child_1 <= key_1 <= ... <= key_(N - 1) <= child_N
std::ptrdiff_t N_ = 0;
Node *parent_ = nullptr;
Node() : keys_(alloc_.allocate(2 * t - 1)) {
children_.fill(nullptr);
}
~Node() noexcept {
alloc_.deallocate(keys_, 2 * t - 1);
}
Node(const BTreeNodeBase &node) = delete;
Node &operator=(const BTreeNodeBase &node) = delete;
Node(BTreeNodeBase &&node) = delete;
Node &operator=(BTreeNodeBase &&node) = delete;
};
Here, alloc_
is an allocator of BTree
.这里,
alloc_
是BTree
的分配器。 Of course, value_type
of alloc_
is K
.当然,
alloc_
的value_type
是K
。 I'm using polymorphic allocators, so that it can allocate or deallocate from memory resources from the main memory or the disk file (which will be my main use case).我正在使用多态分配器,以便它可以从主内存或磁盘文件(这将是我的主要用例)的内存资源中分配或取消分配。
keys_
is not initialized, it is just allocated as raw memory. keys_
没有初始化,它只是作为原始内存分配。 I don't want to initialize it at constructor of Node
unless it is really necessary.除非确实有必要,否则我不想在
Node
的构造函数中初始化它。
To get to the point, is it safe to insert key like node->keys[i] = K;
言归正传,插入像
node->keys[i] = K;
这样的键是否安全? ? ? The type restriction of keys is as follows:
键的类型限制如下:
template <typename T>
concept DiskAllocable = std::is_same_v<std::remove_cvref_t<T>, T>
&& std::is_trivially_copyable_v<T> && (sizeof(T) % alignof(T) == 0);
Other than these, there are no more restrictions.除此之外,没有更多的限制。 Is it safe to assign an object of type
T
to uninitialized memory T*
?将类型
T
的对象分配给未初始化的内存T*
是否安全? Or do I need more restrictions?还是我需要更多限制?
如果您使用construct_at
,那么您没有任何限制,并且alloc_.allocate<T>(n)
将为您分配适当分配的内存块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.