从空的define调用析构函数

Call destructor from empty define?

本文关键字:调用 析构函数 define      更新时间:2023-10-16

假设以下头文件:

#ifndef TEST_HEADER
#define TEST_HEADER 
class myFoo
{
    public:
    myFoo(unsigned long *ulbaz):
    baz(ulbaz)
    {
      *baz++;
    }
    ~myFoo()
    {
      *baz--;
    }
    private:
        unsigned long *baz;
    };
#define DEFINE_A( a ) myFoo bar( a);
#define DEFINE_B( b ) 
#endif  // test_header

代码示例:

// code.cpp
#include "test.h"
unsigned long mylong = 0L;

int main()
{
    DEFINE_A( &mylong);
    DEFINE_B( &mylong);
}

如您所见,DEFINE_B为空。我不明白的是:每次调用DEFINE_B时,我都会从myFoo进入析构函数,我可以在调用堆栈中看到这一点——怎么可能呢?据我所知,一个空的define扩展为;

编辑:此代码现在有效。

我假设您正在运行以下main:

int main (int argc, char const* argv[])
{
    unsigned long mylong = 0L;
    DEFINE_A( &mylong);
    DEFINE_B( &mylong);
    return 0;
}

DEFINE_B( b )扩展为零,您可以看到类myFoo的析构函数,因为当到达作用域的末尾时,所有在其中创建的对象都会通过调用其析构函数来删除。

这是由对象超出范围引起的。想象一下下面的例子来证明这一点:

#include <iostream>
#define EXAMPLEMACRO
class Test {
public:
    Test() {}
    ~Test() {}
}
int main() {
    //Open a new scope
    {
        EXAMPLEMACRO //This doesn't do anything!
        Test t();
        EXAMPLEMACRO //This called the destructor?
    }
    return 0;
}

它不调用析构函数,只是你的对象超出了作用域。

此行:

DEFINE_B( &mylong);

将转换为代码。换句话说,这条线上什么都不会发生。