R
Ralf Goertz
Hi,
according to the FAQ, references can be thought of as aliases and I
sometimes used them to avoid lengthy variables. It seems to be possible
to use aliases for pointers like:
#include <iostream>
using namespace std;
int main() {
int i(42);
int* p(&i);
int &r(i);
int* &rp(p);
cout<<"int:\t"<<i<<endl;
cout<<"int*:\t"<<*p<<endl;
cout<<"int&:\t"<<r<<endl;
cout<<"int*&:\t"<<*rp<<endl;
return 0;
}
This compiles fine, but the following:
void foo(someClass* s) {
someOtherClass* &pr(reinterpret_cast<someOtherClass*>(s->ptr));
/* ... */
}
where someClass has a member char *ptr, gives an error with g++:
error: invalid initialization of non-const reference of type
‘someOtherClass*&’ from a temporary of type ‘someOtherClass*’
I can fix this by declaring 'pr' to be a reference to the dereferenced
object:
someOtherClass &pr(*reinterpret_cast<someOtherClass*>(s->ptr));
which might be the better way, anyway. But what is the problem with the
reference to the pointer? Furthermore, does the creation of the
reference lead to substantial overload? The function foo is called a
zillion times and my hope is that 'pr' is optimized away by the compiler
(using -O3). What about the reinterpret_cast, is it done during
compilation? Then I might use a macro instead of a reference.
according to the FAQ, references can be thought of as aliases and I
sometimes used them to avoid lengthy variables. It seems to be possible
to use aliases for pointers like:
#include <iostream>
using namespace std;
int main() {
int i(42);
int* p(&i);
int &r(i);
int* &rp(p);
cout<<"int:\t"<<i<<endl;
cout<<"int*:\t"<<*p<<endl;
cout<<"int&:\t"<<r<<endl;
cout<<"int*&:\t"<<*rp<<endl;
return 0;
}
This compiles fine, but the following:
void foo(someClass* s) {
someOtherClass* &pr(reinterpret_cast<someOtherClass*>(s->ptr));
/* ... */
}
where someClass has a member char *ptr, gives an error with g++:
error: invalid initialization of non-const reference of type
‘someOtherClass*&’ from a temporary of type ‘someOtherClass*’
I can fix this by declaring 'pr' to be a reference to the dereferenced
object:
someOtherClass &pr(*reinterpret_cast<someOtherClass*>(s->ptr));
which might be the better way, anyway. But what is the problem with the
reference to the pointer? Furthermore, does the creation of the
reference lead to substantial overload? The function foo is called a
zillion times and my hope is that 'pr' is optimized away by the compiler
(using -O3). What about the reinterpret_cast, is it done during
compilation? Then I might use a macro instead of a reference.