【发布时间】:2012-09-13 19:31:45
【问题描述】:
使用 boost 进行测试时如何定义自己的 main() 函数?
Boost 使用的是它自己的 main 函数,但我使用的是自定义内存管理器,需要在分配任何内存之前对其进行初始化,否则会出错。
【问题讨论】:
-
在 C++ 中,
main不是方法。
标签: c++ unit-testing boost
使用 boost 进行测试时如何定义自己的 main() 函数?
Boost 使用的是它自己的 main 函数,但我使用的是自定义内存管理器,需要在分配任何内存之前对其进行初始化,否则会出错。
【问题讨论】:
main 不是方法。
标签: c++ unit-testing boost
我不相信你真的需要你自己的主。我认为global fixture 会更好:
struct AllocatorSetup {
AllocatorSetup() { /* setup your allocator here */ }
~AllocatorSetup() { /* shutdown your allocator/check memory leaks here */ }
};
BOOST_GLOBAL_FIXTURE( AllocatorSetup );
【讨论】:
你必须定义
BOOST_TEST_NO_MAIN
在提升包括之前。
BOOST_TEST_MAIN
是默认值。 http://www.boost.org/doc/libs/1_36_0/libs/test/doc/html/utf/compilation.html
【讨论】:
你可以定义一个静态对象,他的构造函数会在main之前执行:
class Alloc_Setup {
Alloc_Setup() {
// Your init code
}
~Alloc_Setup() {
// Your cleanup
}
};
Alloc_Setup setup;
int main() {} // (generated by boost)
【讨论】:
内存可以在main之前分配:
static int* x = new int(1);
int main() { return *x; }
您也可以将内存管理器设为全局变量,
但是您不能强制执行全局变量初始化的特定顺序。 (至少在标准 C++ 中)
在 Windows 中,您可以将内存管理器放入 DLL 中,在调用应用程序入口点之前将对其进行初始化,但是,其他东西可能会在之前分配内存 - 另一个 DLL,或 DLL 的 CRT。
【讨论】: