c++在未初始化内存中赋值对象



我正在为数据库编写一个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;
};

这里,alloc_BTree的分配器。当然,alloc_value_typeK。我正在使用多态分配器,以便它可以从主内存或磁盘文件(这将是我的主要用例)中分配或释放内存资源。

keys_没有初始化,它只是作为原始内存分配。我不想在Node的构造函数中初始化它,除非真的有必要。

要达到这一点,它是安全的插入键像node->keys[i] = K;吗?键的类型限制如下:

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);

除了这些,没有更多的限制。将类型为T的对象分配给未初始化的内存T*是否安全?还是我需要更多的限制?

如果你使用construct_at,那么你没有任何限制,alloc_.allocate<T>(n)将为你分配一个适当分配的内存块。

最新更新