简体   繁体   English

将unsigned int *'转换为'unsigned int *&

[英]convert unsigned int *' to 'unsigned int *&

I have a function which gets 'unsigned int *& argument The parameter I want to transfer in my code is located in the std::vector<unsigned int> data So,what I do is : I transfer the following parameter &data[0] But get the compilation error: 我有一个函数,它得到'unsigned int *&argument我想在我的代码中传递的参数位于std::vector<unsigned int> data所以,我做的是:我传输以下参数&data [0]但是得到编译错误:

unsigned int *' to 'unsigned int *&

What can be a work around? 什么可以解决? Thanks, 谢谢,

&data[0] is an rvalue and cannot be bound to non-const reference. &data[0]是一个rvalue,不能绑定到非const引用。

You can make it work this way: 你可以这样工作:

unsigned int *ptr = &data[0];
func(ptr);

But possibly it's better to just change the signature of your function to 但是,将函数的签名更改为可能更好

void foo(unsigned int &val); //or any other return type

There is a sense of passing a reference to a pointer in case you want to make a pointer point somewhere else. 如果您想在其他位置创建指针点,则可以传递对指针的引用。 But I don't see a reason to do so in your case 但在你的情况下我没有理由这么做

The expression &data[0] yields indeed an r-value, which your function cannot accept. 表达式&data[0]确实产生了一个r值,你的函数无法接受。

A simple work-around if you don't want to alter your function (make sure you understand the reasons it requires a reference): 如果您不想改变您的功能,请进行简单的解决方法(确保您了解需要参考的原因):

unsigned int* ptr = &data[0];
func(ptr);

&data[0] is a rvalue, but the function parameter type is non-constant reference to a pointer. &data [0]是一个rvalue,但函数参数类型是指针的非常量引用。 A non-const reference can't be bound to an rvalue. 非const引用不能绑定到右值。

It's hard to suggest a good workaround until OP provides more context for his problem. 在OP为他的问题提供更多背景之前,很难建议一个好的解决方法。

Write

unsigned int *argument = &data[0];
call_function(argument);

Be aware that the function may be expecting to change the value of argument , so it may expect you to then write: 请注意,该函数可能希望更改argument的值,因此可能希望您编写:

data.assign(argument, argument + new_length);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM