从空的define调用析构函数
Call destructor from empty define?
假设以下头文件:
#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);
将转换为代码。换句话说,这条线上什么都不会发生。
相关文章:
- 什么时候调用析构函数
- C++-明确何时以及如何调用析构函数
- C++ 防止在映射中放置()时调用析构函数
- 调用析构函数以释放动态分配的内存
- C++:使用方法调用析构函数的顺序是什么?
- 向量推回调用析构函数时调用析构函数
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- C++,我应该调用析构函数吗?
- 如何获取有关在 Clang LibTooling 中调用析构函数的信息?
- 当我从 std::vector 中的新放置调用析构函数时会发生什么?
- 为什么这里不调用析构函数
- 在调用 std::bind 的产品后意外调用析构函数
- 为什么在传递给函数而不是构造函数时调用析构函数?
- 如何在C++中调用析构函数
- 为什么为未删除的对象调用析构函数?
- 调用析构函数时出错
- C++ 在不释放内存的情况下调用析构函数
- 为什么在运算符删除中不调用析构函数?
- C++ 调用析构函数后动态模板队列"double free or corruption (out)"
- 在 postOrderDelete 上调用析构函数时引发的异常