首先要注意在C++中,不像在Java中,用户可以定义值类型。这意味着对于routing_entry有2^32 * 2^32 * 2^8个可能的值。如果你愿意,你可以将routing_entry想象成一个72位的原始类型,尽管你必须小心这个类比。
因此,在Java中route
可以为空,并且对于routing_entry
变量有2^32 * 2^32 * 2^8 + 1有用的不同值。在C++中,它不能为空。在Java中“空”可能意味着返回一个空引用。在C++中,只有指针可以为空,并且routing_entry
不是指针类型。因此,在这种情况下,你的代码中的“空”意味着“我不知道这个东西有什么价值,因为我从来没有初始化它或分配给它”。
在Java中,将在堆上分配一个routing_entry
对象。在C++中,除非必须这么做,否则不需要这样做,因为C++中的内存管理需要付出努力。
你有几个(好)选项:
1)字段添加到路由表项,以表明它已被初始化。可能这不会让的,因为你的执行填充和对齐需求结构的任何更大,:
struct routing_entry {
unsigned long destSeq; // 32 bits on Win32. Could be different.
unsigned long nextHop // 32 bits on Win32. Could be different.
unsigned char hopCount; // 8 bits on all modern CPUs. Could be different.
unsigned char initialized; // ditto
};
为什么不使用布尔?因为标准有用地允许sizeof(bool) != 1
。 bool完全可以作为int来实现,特别是如果你有一个古老的C++编译器。这会让你的结构更大。
然后确保结构也是在你的函数inited 0值,是在栈上的,而不是什么垃圾:
routing_entry Cnode_router_aodv::consultTable(unsigned int destinationID) {
routing_entry route = {};
if (routing_table.find(destinationID) != routing_table.end())
route = routing_table[destinationID];
return route; // will be "empty" if not found
}
,并确保在地图中所有entriess有初始化字段设置为非零。呼叫者然后检查初始化。
2)使用现有字段的“魔术”值作为标记。
假设为了论证,你从不处理hopCount 0的路由。然后只要你如上所述0初始化,调用者可以检查hopCount!= 0。类型的最大值也是好标志值 - 因为你限制你的路由为256跳,所以你不会将它们限制在255跳以内。而不必记住这个呼叫者的方法添加到结构:
struct routing_entry {
unsigned long destSeq; // 32 bits
unsigned long nextHop // 32 bits
unsigned char hopCount; // 8 bits
bool routeFound() { return hopCount != (unsigned char)-1; }
};
然后你初始化像这样:
routing_entry route = {0, 0, -1};
,或者如果你担心,当你更改顺序会发生什么或将来字段数:
routing_entry route = {0};
route.hopCount = -1;
,且调用者:
routing_entry myroute = consultTable(destID);
if (myroute.routeFound()) {
// get on with it
} else {
// destination unreachable. Look somewhere else.
}
3)调用者通过指针或非const引用传入routing_entry
。被调用者填写答案,并返回一个值,表示它是否成功。这通常被称为“外部参数”,因为它有点模拟返回一个布尔型的函数返回routing_entry
和。
bool consultTable(unsigned int destinationID, routing_entry &route) {
if (routing_table.find(destinationID) != routing_table.end()) {
route = routing_table[destinationID];
return true;
}
return false;
}
调用程序:
routing_entry route;
if (consultTable(destID, route)) {
// route found
} else {
// destination unreachable
}
顺便说一句,使用的地图,当你的代码,因为它是查找该ID两次。您可避免这种 如下,虽然它不可能使一个明显的区别,以您的应用程序的性能:
map< unsigned long int, routing_entry >::iterator it =
routing_table.find(destinationID);
if (it != routing_table.end()) route = *it;
谢谢大家,我收到了很多非常有帮助的评论,他们真的打开了我的眼睛。我是C++的新手,但我坚持使用它,因为我正在为我的主人使用遗留代码。 最后,我必须选择一个答案,但我赞成所有那些启发了我的答案。再次感谢:) – sabbour 2009-06-19 11:44:37