Here's the essence of the code:
class DM
{
public:
int something;
DM() : something(0) { }
};
typedef DM * dm_t;
typedef dm_t & dm_ref_t;
typedef const DM * dm_const_t;
typedef dm_const_t & dm_cref_t;
int getSomething( dm_cref_t dm ) // CALLING getSomething DOES NOT COMPILE
{
return dm->something;
}
int getSomethingAgain( dm_const_t dm )
{
return dm->something;
}
int getSomethingOnceMore( dm_ref_t dm )
{
return dm->something;
}
int main()
{
dm_t dm = new DM;
getSomething( dm ); // COMPILER ERROR COMES FROM HERE
getSomethingAgain( dm );
getSomethingOnceMore( dm );
return 0;
}
And here's the compiler error:
implicit_cast.cpp: In function ‘int main()’:
implicit_cast.cpp:31: error: invalid initialization of reference of type ‘const DM*&’ from expression of type ‘DM*’
implicit_cast.cpp:13: error: in passing argument 1 of ‘int getSomething(const DM*&)’
That is, I have a non-const pointer that I'd like to pass into a function that accept a const pointer by reference. All is fine and dandy if the function would accept a non-const pointer by reference or a const pointer by value, but const pointer by reference does not accept non-const pointer.
For safety reasons I'd like the function to take a const pointer; for some further development reasons I'd like it to be passed by reference. It should be completely safe to automatically cast from non-const to const. Why doesn't g++ performs the cast?
I'd like to proceed further with a function defined like getSomething. How can I legalize these calls without adding explicit casts every time I call it?
This is more like the C++ name "resolution". In your case, you have a pointer to a const DM
, but you want a const pointer, so you must use typedef dm_const_t const & dm_cref_t
(a const reference to a const pointer)
Giving more details:
When you declare const int * a
, you are saying that a
is a constant pointer to an integer. It is the same as int const * a
.
If you want a reference to a type, you declare int & b
, meaning that b
is a reference to an integer. Thinking the same way, const int & c
is the same as int const & c
(const always qualify the variable, not the type).
So, if you want a const reference to a const pointer, using the second notation is clearer (and the only one possible if not using typedef
s): int const * const & d
, meaning d
is a constant reference to a constant pointer to an integer. Using typedefs:
typedef const int * int_cptr;
typedef const int_cptr & int_cptrcref;
Proof: http://ideone.com/V48Kxe
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments