[英]Exact definition of as_bytes function
I found this function while reading and I can't find its definition on CPPreference 我在阅读时发现了这个功能,我无法在CPPreference上找到它的定义
programming Principles by Bjarne stroustrup 编程原则由Bjarne stroustrup撰写
It is used in this way: 它以这种方式使用:
ifs.read(as_bytes(x),sizeof(int));`
I understand how read
works but still can you help me with to_bytes
standard definition. 我理解read
是如何工作的,但你仍然可以帮助我使用to_bytes
标准定义。
The as_bytes
function returns the address of the first byte of the argument (so the read
call will overwrite the object x
). as_bytes
函数返回参数的第一个字节的地址(因此read
调用将覆盖对象x
)。 Therefore in C++11 or later one would write that function as follows: 因此,在C ++ 11或更高版本中,可以按如下方式编写该函数:
template <class T>
char* as_bytes(T& x) {
return &reinterpret_cast<char&>(x);
// or:
// return reinterpret_cast<char*>(std::addressof(x));
}
The version linked in the comments predates C++11. 注释中链接的版本早于C ++ 11。 Presumably the reason why Stroustrup converts first to void*
is because reinterpret_cast
is not guaranteed to do the right thing in C++03. 据推测,Stroustrup首先将其转换为void*
的原因是因为reinterpret_cast
不能保证在C ++ 03中做正确的事情。 Note also that the old version will not work correctly for an argument that has an overloaded &
operator. 另请注意,对于具有重载&
运算符的参数,旧版本将无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.