Reputation: 12249
I was looking at http://msdn.microsoft.com/en-us/library/szywdw8k%28VS.80%29.aspx and part of the code didn't make sense to me.
int iVar;
const long& LongRef3 = iVar; // OK
Why can LongRef3 reference iVar even though they are different types when LongRef3 is declared constant?
According to this: Why does the constness of a reference affect whether it can be initialized with a variable of a different type?
"Because it creates a temporary int where the double is converted, and mutable references cannot bind to temporaries, whereas const ones can." That doesn't make sense to me. What temporary int is being created?
Why would I want to do this? When would it be useful over declaring it const int&?
And is there a limit to which types I can do this with?
EDIT: Why was this question down voted? I believe I explained the question pretty well.
Upvotes: 0
Views: 147
Reputation: 179930
"Why not a const int&" ?
You may not have a choice:
int foo(); // Not provided by you.
void bar(const long&); // Not provided by you either.
bar(foo()); // Works because the temporary long is bound.
Upvotes: 0
Reputation: 477228
This is just one facet of a general C++ feature which allows constant references to bind to temporaries, and in the process extending the life of the temporary. Behold:
Foo bar();
void f()
{
bar(); // temporary dies at the semicolon
const Foo & x = bar(); // temporary has its lifetime extended...
// ...
} // ... and dies only here, at the end of x's lifetime
As noted elsewhere, your original code creates a temporary long
, which is then bound to the const reference.
Extending the lifetime of a temporary may be desirable if you don't want to make a copy or move, or rely on RVO. It's probably not one of the most useful features of the language, but there you have it.
Upvotes: 0
Reputation: 81369
int iVar;
const long& LongRef3 = iVar;
The reference LongRef3
does not reference iVar
, but a temporary value of type long
initialized from the value of iVar
. The code is somewhat similar to this:
int iVar;
const long __injected_iVar__ = iVar;
const long& LongRef3 = __injected_iVar__;
You could try and see what happens when you do &iVar
vs &LongRef3
.
Why would I want to do this? When would it be useful over declaring it const int&?
In such simple cases, it may not be useful. However if a function argument takes something by const reference, then you can use compatible types and even literals as such argument.
And is there a limit to which types I can do this with?
Only for compatible types; but it does apply to user defined structs and classes as well, as long as they provide conversions between them.
Upvotes: 9