我正在围绕一个遗留API编写一个C++包装器。这个API为我提供了一个指针值来保存额外的数据,我想用它实现小的缓冲区优化。
我实现了一个is_small_pod元功能,它检查给定的类型是否符合void*。
template< typename Type >
struct is_small_pod
: std::integral_constant<
bool
, std::is_pod< Type >::type::value
&& sizeof( Type ) <= sizeof( void* )
>
{};我是这样设定价值的:
// void*& param;
if( detail::is_small_pod< Type >() )
{
*static_cast< Type* >( ¶m ) = value;
} else {
param = new Type( value );
}我是否正确地实现了这个优化?我相信,当值对齐与指针的对齐不兼容时,这将失败(可能是奇数角情况)。这种情况有可能发生吗,还是我想得太多了?我应该如何扩展我的元功能来检查兼容的对齐方式?
发布于 2012-10-25 21:14:46
类型的对齐不可能大于该类型的大小。
3.11对齐basic.align是一个实现-defined整数值,表示可以分配给定对象的连续地址之间的字节数。 5.3.3 expr.sizeof的独立性 2-.N个元素数组的大小是元素大小的n倍。
因此,您的代码只有在alignof(void *) < sizeof(void *)时才能中断,而在大多数平台上并非如此。
为了安全起见,你可以写:
template< typename Type >
struct is_small_pod
: std::integral_constant<
bool
, std::is_pod< Type >::type::value
&& sizeof( Type ) <= sizeof( void* )
&& alignof( Type ) <= alignof( void* )
>
{};发布于 2012-10-25 21:17:58
作为一种一般的方法,你总是可以尝试测试你的理论。我想你会这样做:
template< class Type >
bool TestAlignmentSanity( Type value )
{
// This function is only valid for small POD types
if( !detail::is_small_pod< Type >() )
return false;
// Temporary space covering alignments spanning the size of a void*
const int nBytes = sizeof(void*);
char buffer[sizeof(Type) + nBytes - 1];
// For each target alignment, test that a copy is successful.
for( int i = 0; i < nBytes; i++ )
{
Type * target = static_cast< Type* >( &buffer[i] );
// Sanity-check that the pointer was actually aligned as we requested
if( (char*)target != &buffer[i] ) return false;
// Copy and test that the result is as expected. Assumes '==' operator
// is defined... Otherwise, implement with byte comparisons.
*target = value;
if( !(*target == value) ) return false;
}
return true;
}在这里,我测试了数据类型可以复制到跨void*大小的任何对齐中。这只是一个想法。=)
https://stackoverflow.com/questions/13077086
复制相似问题