can't pass by reference a pointer returned from a function

99封情书 提交于 2019-12-11 08:17:07

问题


why I need intermediate variable to pass my return pointer by reference instead of just using the function that returns that pointer ?

This doesn't compile

int main ()
{
  testfunc(getpointer());
  return 0;
} 

error: C2664: 'void testfunc(int *&)': cannot convert argument 1 from 'int *' to 'int *&'

and this compiles

int main ()
{
   int *i = getpointer();
   testfunc(i);
   return 0; 
} 

my two functions

void testfunc(int *& i) // I have to use this interface
{
  cout << i[0] <<endl;
}

int* getpointer()
{
  int * arr1 = new int[1];
  arr1[0]=10;
  return arr1;
}

回答1:


The C++ language prohibits binding a non-const reference to a temporary. In this case, the simple fix is to make testfunc take a const reference to an int*.



来源:https://stackoverflow.com/questions/39883808/cant-pass-by-reference-a-pointer-returned-from-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!