【发布时间】:2014-02-27 03:45:22
【问题描述】:
我有一个看起来像这样的函数:
template<typename T>
void some_function(T* buffer) {
BOOST_STATIC_ASSERT(sizeof(T) <= sizeof(unsigned int));
unsigned int temporary_buffer;
int result = some_c_api(&temporary_buffer);
if(result == error)
throw some_exception();
// originally *buffer = reinterpret_cast<T&>(temporary_buffer), but this breaks
// strict aliasing
std::copy( reinterpret_cast<char*>(&temporary_buffer),
reinterpret_cast<char*>(&temporary_buffer) + sizeof(T),
reinterpret_cast<char*>(buffer));
}
在这里将两个不相关的缓冲区都转换为char* 并复制目标缓冲区可以容纳的字节数是否安全?我正在使用非 C++11 编译器 (gcc 4.1.2)。
我在重构一些代码时遇到了这个问题。原始代码没有此警告,因为它以void* 传递缓冲区。我认为这是非法的是否正确?
【问题讨论】:
-
temporary_buffer真的是unsigned int吗?你真的从unsigned ints 地址复制sizeof(T)字节吗?sizeof(T) <= sizeof(unsigned int)有什么保证吗? -
是的,确实是这样。函数开头有静态断言,确保
sizeof(T) <= sizeof(unsigned int)。 -
哎呀,完全错过了断言。
标签: c++ reinterpret-cast strict-aliasing type-punning