Using a custom allocator, it is possible to build a vector with a size known only at run time (so no std::array
possible), wrapping an existing array. It is even possible to keep pre-existing values by overriding the special construct
method(*).
Here is a possible implementation:
/**
* a pseudo allocator which receives in constructor an existing array
* of a known size, and will return it provided the required size
* is less than the declared one. If keep is true in contructor,
* nothing is done at object construction time: original values are
* preserved
* at deallocation time, nothing will happen
*/
template <class T>
class SpecialAllocator {
T * addr;
size_t sz;
bool keep;
public:
typedef T value_type;
SpecialAllocator(T * addr, size_t sz, bool keep):
addr(addr), sz(sz), keep(keep) {}
size_t max_size() {
return sz;
}
T* allocate(size_t n, const void* hint=0) {
if (n > sz) throw std::bad_alloc(); // throws a bad_alloc...
return addr;
}
void deallocate(T* p, size_t n) {}
template <class U, class... Args>
void construct(U* p, Args&&... args) {
if (! keep) {
::new((void *)p) U(std::forward<Args>(args)...);
}
}
template <class U>
void destroy(U* p) {
if (! keep) {
p->~U(); // do not destroy what we have not constructed...
}
}
};
It can then be used that way:
int size = 5; // This is not a constant in general
int *my_array = SpecialAllocationFunction(size);
SpecialAllocator<int> alloc(my_array, size);
std::vector<int, SpecialAllocator<int> > vec(size, alloc);
From that point, vec
will be a true std::vector
wrapping my_array
.
Here is a simple code as demo:
int main(){
int arr[5] = { 5, 4, 3, 2, 1 };
SpecialAllocator<int> alloc(arr, 5, true); // original values will be preserved
std::vector<int, SpecialAllocator<int> > vec(5, alloc);
for(auto it= vec.begin(); it != vec.end(); it++) {
std::cout << *it << " ";
}
std::cout << std::endl;
try {
vec.push_back(8);
}
catch (std::bad_alloc& a) {
std::cout << "allocation error" << std::endl;
}
return 0;
}
It will successfully output:
5 4 3 2 1
allocation error
(*) BEWARE: Construction/destruction may be involved in different places: push_back
, emplace_back
, etc. Really think twice about your real use case before using no-op construct
and destroy
methods.