C/C++模式到USE_HEAP或USE_STACK

Cha*_*les 3 c c++ heap stack memory-management

有没有办法定义一个宏(或类似的东西),允许对象在堆栈上或堆上分配,干净利落?

例如.当前代码:

A a;
a.someFunc();
Run Code Online (Sandbox Code Playgroud)

最简单的建议可能如下,但正如您在下面所看到的,维护2组代码并不是很干净.

#ifdef USE_STACK
  A a;
  a.someFunc();
#elseif USE_HEAP
  A* a = new A();
  a->someFunc();
#endif
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种设计模式/代理类,可以用来编译代码,这取决于我们客户的需求.

编辑:该代码用于为嵌入式设备/(嵌入式)Linux/Windows Mobile构建库.大多数客户只需要基于堆栈的分配.其他一些人要求交易堆栈.

谢谢,查尔斯

Eva*_*ran 5

编辑:改进,允许通过调用包装成员函数operator->

扩展曼努埃尔的答案,使其更完整,试试这个:

#include <iostream>

#define USE_STACK

template <class T>
class HeapWrapper {
#ifdef USE_STACK
    T obj_;
#else
    T *obj_;
#endif
public:
#ifdef USE_STACK
    HeapWrapper() : obj_() {}

    template <class A1>
    HeapWrapper(const A1 &a1) : obj_(a1) {}

    template <class A1, class A2>
    HeapWrapper(const A1 &a1, const A2 &a2) : obj_(a1, a2) {}

    // etc

#else
    HeapWrapper() : obj_(new T()) {}
    ~HeapWrapper() { delete obj_; }

    template <class A1>
    HeapWrapper(const A1 &a1) : obj_(new T(a1)) {}

    template <class A1, class A2>
    HeapWrapper(const A1 &a1, const A2 &a2) : obj_(new T(a1, a2)) {}

    // etc
#endif

#ifdef USE_STACK
    operator const T &() const    { return obj_; }
    operator T &()                { return obj_; }
    T *operator->()               { return &obj_; }
    T& operator*()                { return obj_; }
#else
    operator const T &() const    { return *obj_; }
    operator T &()                { return *obj_; }
    T *operator->()               { return obj_; }
    T& operator*()                { return *obj_; }
#endif

    // cast operators makes this work nicely
    HeapWrapper &operator=(const T &rhs) { *obj_ = rhs; return *this;}
};


class A {
public:
    void member(int x) {
        std::cout << x << std::endl;
    }
};


int main() {
    HeapWrapper<int> x1(5);
    HeapWrapper<int> x2;
    HeapWrapper<int> x3 = x1;
    HeapWrapper<int> x4 = 3;

    std::cout << x1 << " " << x2 << " " << x3 << " " << x4 << std::endl;

    // example using a custom class's members..
    HeapWrapper<A> a1;
    a1->member(5);
}
Run Code Online (Sandbox Code Playgroud)