[英]How to cast a pointer in C++
void foo(void **Pointer);
int main ()
{
int *IntPtr;
foo(&((void*)IntPtr));
}
Why do I get an error? 为什么我会收到错误?
error: lvalue required as unary ‘&’ operand
Thanks 谢谢
void foo(void **Pointer);
int main ()
{
int *IntPtr;
foo((void**)&IntPtr);
}
When you do 当你这样做
(void*)IntPtr
you create a temporary variable, which is only an rvalue, and so can't be dereferenced. 您创建一个临时变量,它只是一个右值,因此无法解除引用。
What you need to do is: 你需要做的是:
int main()
{
int* IntPtr;
void* VoidPtr = (void*)IntPtr;
foo(&VoidPtr);
}
or equivalent 或同等学历
(void*) is not an lvalue, it is kind of a casting operator, you need to have the ampersand to the immediate left of the variable (lvalue). (void *)不是左值,它是一种构造运算符,你需要在变量(左值)的左边有一个&符号。 This should be right:
这应该是对的:
foo(((void**)&IntPtr));
More C++ style: 更多C ++风格:
foo( reinterpret_cast< void** >( IntPtr ) );
But remember, according to Standard such a cast is implementation specific. 但请记住,根据标准,这样的演员阵容是特定于实现的。 Standard gives no guarantees about behavior of such cast.
标准不保证这种演员的行为。
As others point out, you have the order of the cast and the &
wrong. 正如其他人指出的那样,你有演员的顺序
&
错误。 But why do you use void**
at all? 但是你为什么要使用
void**
呢? That means that you accept a pointer to a void pointer . 这意味着您接受指向void指针的指针 。 But that's not at all what you want.
但那根本不是你想要的。 Just make the parameter a
void*
, and it will accept any pointer to some object: 只需将参数设为
void*
,它将接受任何指向某个对象的指针:
void foo(void*);
int main () {
int *IntPtr;
foo(&IntPtr);
assert(IntPtr == NULL);
}
That's what void*
is for. 这就是
void*
的含义。 Later, cast it back using static_cast
. 稍后,使用
static_cast
将其static_cast
回来。 That's a quite restrictive cast, that doesn't allow dangerous variants, unlike the C style cast (type) : 这是一个相当严格的演员,不允许危险的变体,不像C风格演员(类型) :
void foo(void* p) {
int** pint = static_cast<int**>(p);
*pint = NULL;
}
If the function takes pointers to void*
, then that function can't accept pointers to int*
. 如果函数接受指向
void*
指针,那么该函数不能接受指向int*
指针。 But if the function accepts either or, then the function should accept void*
, and you should cast to the proper type inside the function. 但是如果函数接受了或者,那么函数应该接受
void*
,并且你应该在函数内部转换为正确的类型。 Maybe paste what you really want to do, we can help you better then. 也许粘贴你真正想做的事情,我们可以更好地帮助你。 C++ has some good tools available, including templates and overloading, both of which sound helpful in this case.
C ++提供了一些很好的工具,包括模板和重载,在这种情况下这两种工具都很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.