Thursday, 5 September 2013

static new per each invocation possible?

static new per each invocation possible?

What are the possible ways to write a static_new function sort of like
this one, that will return a unique instance per each invocation?
template <typename T, ::std::size_t, typename ...A>
static void* static_new(A&& ...args)
{
static T v(::std::forward<A>(args)...);
return &v;
}
int main()
{
std::cout << static_new<int, __COUNTER__>() << std::endl;
std::cout << static_new<int, __COUNTER__>() << std::endl;
std::cout << static_new<int, __COUNTER__>() << std::endl;
std::cout << static_new<int, __COUNTER__>() << std::endl;
return 0;
}
The function I have provided does not fulfill the requirements. First, I
need to help it with the __COUNTER__ macro. Second, static_new may well
get instantiated and called twice with the same T and the same
__COUNTER__. I was thinking about arrays:
static std::aligned_storage<sizeof(T), alignof(T)> store[some_magic_number];
and placement new into it. Perhaps something better exists?

No comments:

Post a Comment