Is there any standard compliant way to emulate 'return' with macro?
Currently, I'm trying to wrapping _alloca function to emulate variable length array on stack (which is supported in C99) with macro in C++. Since the _alloca function manipulates stack pointer, I think inline function isn't suitable solution for this time.
Below is the current code that I've written.
template <typename T>
inline void __placement_new_array(T arr[], const size_t size) {
assert(size > 0);
for (size_t i = 0; i < size; i++) {
new (&arr[i]) T;
}
}
template <typename T>
class __arraydtor
{
public:
__arraydtor(T arr[], size_t size) : arr_(arr), size_(size) {}
~__arraydtor() {
for (size_t i = size_ - 1; i != (size_t)(-1); i--) {
arr_[i].~T();
}
}
private:
T* arr_;
size_t size_;
};
#define stack_alloc(size) _alloca(size)
#define stacknew(ptr, type, size) \
ptr = static_cast<type*>(stack_alloc(sizeof(type) * size));\
__placement_new_array(ptr, size);\
__arraydtor<type> __##type##_dtor_instance(ptr,size)
...
type* pos;
stacknew(pos, type, size);
I think the code is fairly usable even for now (it works for most type at least in vs2005), but ultimately I want to acheive the macro that can be used like below -
pos = stacknew(type, size);
(Of course pos = stacknew type[size]; would be more cool but I don't think there is a way to acheive it with any C++ compiler)
Since the macro contains some declaration, emulating 'return' is impossible in the current form - it might be impossible or needs a different approach. But I'm lack of experience for using macro, I can not judge whether it's possible or not.
Also I want to note that above code is not safe when the ctor of the target array throws exception - I'd also be grateful if someone suggests a way to improve the macro.