我想为我正在编写的库编写一些单元测试
我有一个看起来像这样的类:
class A
{
public:
A(B* pB)
// construction details, involves my library
// but ultimately there is a new being done ,)
B* m_pB;
};
我想检查指针 m_pB 是否已实际初始化,所以我按照这些行做了一些事情:
A* p = // creation of this object involves my library
BOOST_REQUIRE( p->m_pB != NULL );
但碰巧 g++ 没有对内存进行零初始化,所以 p->m_pB
的值只是随机的。当我 new
对象时,有没有办法强制 g++ 为我将此内存初始化为零?
我相信 Visual Studio 会根据内存的分配位置对特定代码执行类似的操作。
编辑:我现在可以想到 2 个备份解决方案:使用智能指针,或者编写一个新的运算符......
最佳答案
只需实现默认构造函数即可。这保证了在不传递参数的情况下,指针被初始化为 NULL。
class A
{
public:
A(B* pB)
// construction details, involves my library
// but ultimately there is a new being done ,)
A() : m_pB(NULL) {}
B* m_pB;
};
或者正如 Fritschy 指出的那样:
A() : m_pB() {}
关于c++ - 强制 g++ 归零初始化内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6739186/