临时对象持有者和链分配的宏

时间:2017-12-18 10:52:35

标签: c++ macros

假设我们有一个类TestClass,它提供了一个移动构造函数和一个移动赋值运算符。

class TestClass {
    int data;
public:
    TestClass() : data(0) {}
    TestClass(TestClass const & other) = delete;
    TestClass& operator=(TestClass const & other) = delete;
    TestClass(TestClass&& other) : data(other.data) {
    }
    TestClass& operator=(TestClass&& other)  {
        data = other.data;
        return *this;
    }
};

我们希望用宏封装它,以便用户可以调用宏来创建实例,例如

#define TESTCLASS() TestClass()

auto instance = TESTCLASS(); 

这很有效,除了每次用户必须声明一个instance变量来保存实例。如果用户写

TESTCLASS(); 

只会创建一个临时实例并立即死亡。

如果用户可能忘记声明实例变量,我宁愿使用带有临时变量的宏来保存实例。

#define TESTCLASS_HOLDER() \
           TEMPORARY_HOLDER_IN(CONCAT(TEMP_, __LINE__))

#define CONCAT(A, B) CONCAT_IMPL__(A, B)
#define CONCAT_IMPL__(A, B) A ## B

#define  TEMPORARY_HOLDER_IN(tempoary)   auto tempoary = TestClass()

通过这种方式,我们可以将实例保存为临时变量。

TESTCLASS_HOLDER();

但是,由于此变量是临时的,因此用户无法引用它。我们需要的是像TESTCLASS_HOLDER()这样的宏,但如果用户声明了其他变量,则能够std::move实例。

NEW_TESTCLASS_HOLDER();  // let this works together with the next line if any.
auto mytestclass = NEW_TESTCLASS_HOLDER(); //kind of chain assignment?

问题是如何编写这样的宏NEW_TESTCLASS_HOLDER()

0 个答案:

没有答案
相关问题