기본 제어 블록의 종류와 함께 제네릭 유형의 배열을 동적으로 할당하려고합니다. 이것을이 "제어 블록"의 예시 코드로 취하십시오.
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;
}
내가 염려하는 것은 :
한 가지 예 :
#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 ++ 버전입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다