Re: C++. Error while passing pointer by reference.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Andrew Haley wrote:
Kirill Berezin wrote:
Hie.

I crossed the very curious sample of code the gcc failed to compile.
Here is the example:

#include <stdio.h>
#include <stdlib.h>

class test {
public:
      int func(int*& a1){
              a2 = a1;
              return 0;
      }
      void print(){ printf("0x%X \n", a2);};
private:
      int* a2;
};

int main(){
      int* a;
      int c;
      test b;
      //
      b.func(&c);
      b.print();
      return 0;
}
с++ prints the following error

test05.cc: In function 'int main()':
test05.cc:27: error: no matching function for call to 'test::func(int*)'
test05.cc:12: note: candidates are: int test::func(int*&)

I think that it is reasonable not to compile, because, for example, it
would not possible to guess a correct function to overload. But The C++
standard, at first glance, does not prohibit such a coding style.

Doesn't it?

&c yeilds an rvalue of type int*, and you're trying to pass it
as an lvalue to a function.  I presume you're not actually
trying to use an rvalue reference here.

Fix it this way:

      int func(int *const & a1){
              a2 = a1;
              return 0;
      }

Andrew.
Thank you, this is very helpful. It looks like my knowledge of const qualifiers is not deep enough.
Kirill.

--
Кирилл Березин <kyb22@xxxxxx>
Старший инженер-программист
Группа развития ISP систем, Совинтел
Группа Компаний ВымпелКом


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux