在来自 mongodb 的 C++ 驱动程序的一个非常简单的示例中使用 valgrind,一旦我们在 BSONObj 的定义中明确使用 GENOID,就会出现问题。这是一个说明问题的示例:
(在 gcc 4.4.5、boost 1.42、debian 6、mongodb C++ 驱动程序 2.2 上测试)
#include <cstdio>
#include <string>
#include "mongo/db/jsobj.h"
main()
{
mongo::BSONObj p = BSON( mongo::GENOID << "name" << "Joe" << "age" << 33 );
std::string s = p.toString();
std::cout << s;
}
使用 valgrind 运行时,我们会收到以下消息:
==2506== Use of uninitialised value of size 8
==2506== at 0x40A66B: mongo::toHexLower(void const*, int) (hex.h:64)
==2506== by 0x40A73F: mongo::OID::str() const (oid.h:66)
==2506== by 0x40A798: mongo::operator<<(mongo::StringBuilderImpl<mongo::TrivialAllocator>&, mongo::OID const&) (oid.h:140)
==2506== by 0x40DCC1: mongo::BSONElement::toString(mongo::StringBuilderImpl<mongo::TrivialAllocator>&, bool, bool, int) const (bson-inl.h:765)
==2506== by 0x40C898: mongo::BSONObj::toString(mongo::StringBuilderImpl<mongo::TrivialAllocator>&, bool, bool, int) const (bson-inl.h:475)
==2506== by 0x40C5A5: mongo::BSONObj::toString(bool, bool) const (bson-inl.h:445)
==2506== by 0x40A1B8: main (mongobug.cc:10)
如果我从 BSONObj 定义中删除 GENOID,问题就消失了。这是我在项目中使用 mongo::OID::gen() 时遇到的更复杂但类似问题的极简版本。
上面的例子取自这里的官方 mongodb C++ 驱动教程:http ://www.mongodb.org/pages/viewpage.action?pageId=133415#C%2B%2BTutorial-BSON
知道有什么问题吗?谢谢,