与其所有者一起分配阵列的正确方法
Proper way of allocating array together with its owner
我正在尝试动态分配一个通用类型的数组以及一种原始控制块。将此作为此"控制块"的检查代码:
template<class T>
struct my_array{
T* arr;
unsigned size;
};
为了避免多次分配,我尝试只调用分配new
一次。这是我想出的代码:
template<class T>
my_array<T> *alloc_new_array(unsigned size){
unsigned align_mismatch = sizeof(my_array<T>) % alignof(my_array<T>);
unsigned array_size = size * sizeof(T);
unsigned struct_size = sizeof(my_array<T>) + align_mismatch ?
alignof(my_array<T>) - align_mismatch : 0;
char *memory = new char[array_size + struct_size];
my_array<T> *arr = new (memory) my_array<T>;
arr->arr = new (memory + struct_size) T[size];
arr->size = size;
return arr;
}
我关心的是:
- 正确性 - 我想我照顾了结构填充,但我可能缺少一些东西。我是否正确计算了它,无论平台如何,它都能正常工作吗?
- 符合标准 - 我不会违反任何C++规则并导致 UB?我知道我在这里做一些指针魔法,我不确定一切是否完全合法
举个例子:
#include <iostream>
#include <new>
#include <memory>
#include <numeric>
template<class T>
struct alignas(T) WithArray {
unsigned const size_;
static void* operator new(size_t size, unsigned elements) {
return ::operator new(size + elements * sizeof(T));
}
static void operator delete(void* p, size_t /*size*/, unsigned /*elements*/) {
return ::operator delete(p);
}
static void operator delete(void* p) {
return ::operator delete(p);
}
T* get_elements() { return reinterpret_cast<T*>(this + 1); }
T* begin() { return get_elements(); }
T* end() { return get_elements() + size_; }
WithArray(unsigned elements)
: size_(elements)
{
std::uninitialized_default_construct_n(get_elements(), size_);
}
~WithArray() {
std::destroy_n(get_elements(), size_);
}
WithArray(WithArray const&) = delete;
WithArray& operator=(WithArray const&) = delete;
};
int main() {
unsigned elements = 10;
std::unique_ptr<WithArray<int>> a(new (elements) WithArray<int>(elements));
for(int& elem : *a)
std::cout << elem << ' ';
std::cout << 'n';
std::iota(a->begin(), a->end(), 0);
for(int& elem : *a)
std::cout << elem << ' ';
std::cout << 'n';
}
输出:
0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
alignas(T)
+ reinterpret_cast<T*>(this + 1)
是 C99 灵活阵列成员的C++版本。
相关文章:
- 将积分类型的数组作为另一个不相关的积分类型的阵列进行访问的安全且符合标准的方法
- 查找和替换子阵列的最佳方法
- 需要帮助从12个字节生成新的24字节RGB查找阵列,或者是一种更好的编码方法
- 比strncpy更好地复制字符阵列的部分方法
- 重新分配指针阵列的一部分的安全方法
- 从C++与 C 灵活阵列成员互操作的正确方法是什么?
- 比较阵列的更好方法
- VS2017是否有VLA(可变长度阵列)支持解决方法
- 与其所有者一起分配阵列的正确方法
- 在C++使用新方法打印2d阵列
- 适当的标记阵列末端的方法
- 如何通过可行的方法汇总浮点阵列并获得精确的结果
- 通过C 中的2D TIC-TAC-TOE阵列迭代的好方法
- 如何在C中获取char阵列的第一个X元素?提升效果是否有改进的方法
- 检查阵列位置在C++中是否为空的 CPU 高效方法
- 这是遍历阵列的更快方法
- 存储2D对象阵列的最佳方法是什么
- boost::进程间更新阵列的最快方法
- 使用Cuda C将大型2D阵列导出到文件的更快方法
- 增加阵列C++的最有效方法