我想知道是否有理由抛出sizeof的结果? 例:
将sizeof(example)
改为(size_t) sizeof(example)
返回类型是std::size_t
but我在许多函数(malloc,memset,...)中得到错误“无效的争论”,并且在投射之后它起作用。快速检查printf
告诉我,结果保持不变。
-edited- 根据要求提供简短的示例功能:
__cxa_dependent_exception* __cxxabiv1:: __cxa_allocate_dependent_exception() throw()
{
__cxa_dependent_exception *ps_ret;
ps_ret = static_cast<__cxa_dependent_exception *> (o_exception_pool.allocate (
(size_t) sizeof(__cxa_dependent_exception )));
if (!ps_ret)
{
std::terminate ();
}
memset (ps_ret, 0, (size_t) sizeof(__cxa_dependent_exception ));
return ps_ret;
}
没有强制转换,此代码会抛出上述错误。完整的示例可以在gcc 4.5.4源代码“libstdc ++ - v3 / libsupc ++ / eh_alloc.cc”中找到。 我正在使用MinGW。
你的问题浓缩为“你能把std::size_t
转换成另一种类型”。
当然你可以遵守普通的类型转换规则。例如,将它投射到int
可以让你在16位int
的系统上使用非常大的热水。换句话说,检查新类型是否具有足够的容量。
如果你可以在C ++编译时这样做,那就是额外的布朗尼点。
是的,您可以投射sizeof
的结果,因为sizeof(something)
是编译时间,如果(size_t)5
返回sizeof(something)
,您将获得5
类型的结果。