是否有任何符合标准的方法来模拟“返回”宏?
目前,我正在尝试将_alloca函数包装在C ++中用宏来模拟堆栈上的可变长度数组(在C99中支持)。由于_alloca函数操纵堆栈指针,我认为内联函数不适合此时使用。
以下是我编写的当前代码。
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);
我认为代码即使现在也相当可用(至少在vs2005中它适用于大多数类型),但最终我想实现可以像下面这样使用的宏 -
pos = stacknew(type, size);
(当然pos = stacknew type [size];会更酷,但我认为没有办法用任何C ++编译器实现它)
由于宏包含一些声明,因此在当前形式中无法模拟“返回” - 它可能是不可能的,或者需要不同的方法。但是我缺乏使用宏的经验,我无法判断它是否可能。
另外我想要注意的是,当目标数组的ctor抛出异常时,上面的代码是不安全的 - 如果有人提出改进宏的方法,我也会感激不尽。
答案 0 :(得分:0)
您可以使用,
运算符:
v = (expr1, expr2); // evaluate both expressions, return rightmost