I swear I had an interview question like this once, using a char buffer for storage. I think one solution I got from here was to use placement new() as well. I'm not sure if it'll work for primitive types but I think it was the solution for structured/class types.
Edit : Does this violate the aliasing rules cyber mentioned?
Code:
#include <iostream>
struct pair
{
int first, second;
};
template<typename T>
T* push_back(char *buffer,
int &back,
T value)
{
T *data = new(buffer + back) T(value);
back += sizeof(T);
return data;
}
template<typename T>
T* push_back(char *buffer,
int &back)
{
T *data = new(buffer + back) T();
back += sizeof(T);
return data;
}
int main(void)
{
const int buffer_size = 1024;
char buffer[buffer_size];
int back = 0;
int *int_val = push_back<int>(buffer, back, 10);
pair *pair_val = push_back<pair>(buffer, back);
pair_val->first = 20;
pair_val->second = 35;
std::cout << *int_val << std::endl;
std::cout << pair_val->first << std::endl;
std::cout << pair_val->second << std::endl;
}
Edit edit : This compiled quietly with "-std=c++11 -Wall -Wextra -pedantic -O3"