[英]How to Convert Void* into size_t?
I have the following function:我有以下功能:
size_t calc_allign(size_t num) {
return ((num + 7) & (-8)) - num;
}
And want to use it like this:并想像这样使用它:
int start_allign = calc_align (sbrk(0));
But I am getting error:但我收到错误:
error: no matching function for call to 'calc_align'
candidate function not viable: cannot convert argument of incomplete type 'void *' to 'size_t' (aka 'unsigned long') for 1st argument
size_t calc_align(size_t num) {
How may I convert void*
ie a pointer to number?我如何转换void*
即指向数字的指针? is that even something legal?这甚至是合法的吗?
How may I convert void* ie a pointer to number?我如何转换 void* 即指向数字的指针?
You can reinterpret_cast
a pointer type to std::uintptr_t
(or the signed equivalent).您可以reinterpret_cast
指针类型reinterpret_cast
为std::uintptr_t
(或有符号的等效项)。 You can then further convert to another integer type such as std::size_t
and that conversion can be implicit.然后您可以进一步转换为另一种整数类型,例如std::size_t
并且该转换可以是隐式的。 In theory, the latter conversion may be lossy on systems where std::size_t
is a smaller type.理论上,后一种转换在std::size_t
是较小类型的系统上可能是有损的。
However, as far as the C++ language is concerned, there are no guarantees about the resulting number other than converting it back from std::uintptr_t
to the same pointer type will result in the same pointer value.但是,就 C++ 语言而言,除了将其从std::uintptr_t
转换回相同的指针类型将导致相同的指针值之外,无法保证结果数字。
plus can you show some code?另外你能展示一些代码吗?
Example:例子:
void* ptr = sbrk(0);
auto numptr = reinterpret_cast<std::uintptr_t>(ptr);
static_assert(sizeof(std::size_t) >= std::uintptr_t,
"Sorry, it isn't possible to represents pointers using std::size_t on this system");
std::size_t example = numptr;
auto ptr2 = reinterpret_cast<void*>(numptr);
assert(ptr2 == ptr); // guaranteed to pass
why reinterpret_cast not (uintptr_t)?为什么 reinterpret_cast 不是 (uintptr_t)?
The behaviour of explicit conversion aka C-style cast depend on the type of the operand.显式转换又名 C 样式转换的行为取决于操作数的类型。 Some casts are unsafe while others are benign.一些演员是不安全的,而另一些是良性的。 Often simple mistakes cause intended safe cast to be unintendedly unsafe, leading to undefined behaviour (which is very bad) - while the proper C++ style cast would result in compilation error, leading to detection of the mistake (which is very good).通常,简单的错误会导致预期的安全转换意外地不安全,导致未定义的行为(这是非常糟糕的)——而正确的 C++ 风格的转换会导致编译错误,从而导致错误的检测(这是非常好的)。
In case of reinterpret_cast, we are doing such unsafe cast so there is no safety aspect, but instead the importance of C++ style cast is to communicate that lack of safety to the reader of the program.在 reinterpret_cast 的情况下,我们正在执行这种不安全的转换,因此没有安全方面,但 C++ 样式转换的重要性在于向程序的读者传达缺乏安全性。
Don't use the C-style casts in C++.不要在 C++ 中使用 C 风格的强制转换。 You don't need them for anything.你不需要它们做任何事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.