If you use a specific allocator
, you may share the memory.
Something like the following may help:
template <typename T>
struct buffer_allocator
{
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using value_type = T;
buffer_allocator(T* buffer, std::size_t max_size) :
buffer(buffer), max_size(max_size)
{}
template<typename... Args>
void construct(T* p, Args&&... args)
{ /*::new((void *)p) T(std::forward<Args>(args)...);*/ }
void destroy(T* p) { /*p->~T();*/ }
T* allocate(std::size_t n)
{
if (max_size != n) { throw std::bad_alloc{}; }
return buffer;
}
void deallocate(T*, std::size_t) {}
std::size_t get_max_size() const { return max_size; }
private:
T* buffer;
std::size_t max_size;
};
And use it that way: (https://ideone.com/MaDYPZ)
std::vector<int> v{0, 1, 2, 3, 4};
buffer_allocator<int> b1(v.data(), 3);
buffer_allocator<int> b2(v.data() + 3, v.size() - 3);
std::vector<int, buffer_allocator<int>> v1(b1.get_max_size(), b1);
std::vector<int, buffer_allocator<int>> v2(b2.get_max_size(), b2);