初始化
// 简化了 memset 的使用
inline void memZero(void* p, size_t n)
{
memset(p, 0, n);
}
隐式转化
// 用于在继承关系中, 子类指针转化为父类指针;隐式转换
// inferred 推断,因为 from type 可以被推断出来,所以使用方法和 static_cast 相同
template<typename To, typename From>
inline To implicit_cast(From const &f)
{
return f;
}
向下转化继承关系中的指针
template<typename To, typename From> // use like this: down_cast<T*>(foo);
inline To down_cast(From* f) // so we only accept pointers
{
// Ensures that To is a sub-type of From *. This test is here only
// for compile-time type checking, and has no overhead in an
// optimized build at run-time, as it will be optimized away
// completely.
if (false)
{
implicit_cast<From*, To>(0);
}
#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)
assert(f == NULL || dynamic_cast<To>(f) != NULL); // RTTI: debug mode only!
#endif
return static_cast<To>(f);
}
指针向上转化的过程中可以安心的使用 implicit_cast<> 因为都会成功,但是在指针向下的转化中你并不能确定 subclassOfFoo 一定是 foo 的子类,需要使用 dynamic_cast<>来动态的转化来确保没有问题。
在 debug 宏被定义的情况下使用 dynamic_cast<> 避免错误,在实际release版本中使用static_cast 提高速度。