I heard the temporary objects can only be assigned to constant references.
But this code gives error
#include <iostream.h>
template<class t>
t const& check(){
return t(); //return a temporary object
}
int main(int argc, char** argv){
const int &resCheck = check<int>(); /* fine */
typedef int& ref;
const ref error = check<int>(); / *error */
return 0;
}
The error that is get is invalid initialization of reference of type 'int&' from expression of type 'const int'
Your code gives error because the
const
qualifier inconst ref error
is just ignored because8.3.2/1
saysSo
error
has typeint&
notconst int&
.This is compiled:
VC++ compiler gives some explanation of your error: qualifier applied to reference type; ignored. Reference type must be declared as constant, const cannot be applied later.
To maintain consistency with the Right Left Rule, I prefer to use 'cv' qualifiers like so.
In your example, I would write
const ref error = check<int>();
like soAs @Prasoon Saurav pointed out, cv qualifiers are ignored when introduced through typedef because as @GMan also says, that cv qualified references are ill-formed.
Therefore the declaration is effectively as below, which of course is an error.
Check out this for more information.
It's a very common mistake for English speaking people, because of the way the English grammar works.
I consider it extremely unfortunate that the C++ syntax would allow both:
to have the same meaning.
It doesn't make it easier, really, and isn't composable since:
certainly do NOT have the same meaning.
And this, unfortunately for you, what kicks in here, as @GMan explains.
If you wish to avoid this kind of error in the future, take the habit of qualifying your types (
const
andvolatile
) on their right, then you'll be able to treat atypedef
as simple text replacement.This:
Doesn't do what you think it does. Consider instead:
The type of
const_pointer
isint* const
, notconst int *
. That is, when you sayconst T
you're saying "make a type where T is immutable"; so in the previous example, the pointer (not the pointee) is made immutable.References cannot be made
const
orvolatile
. This:is meaningless, so adding cv-qualifiers to references has no effect.
Therefore,
error
has the typeint&
. You cannot assign aconst int&
to it.There are other problems in your code. For example, this is certainly wrong:
What you're doing here is returning a reference to a temporary object which ends its lifetime when the function returns. That is, you get undefined behavior if you use it because there is no object at the referand. This is no better than:
A better test would be:
The return value of the function is a temporary, so you can still test that you can indeed bind temporaries to constant references.