eriwik@student.chalmers.se wrote:
Quote:
Consider this:
>
#include <iostream>
>
template<int A>
struct test {
const int& get() { return A; }
}
>
int main()
{
test<4t;
std::cout << t.get();
}
>
1. Is it legal (it compiles under VC++8).
2. Is it a good idea? At first I thought of having a const int as a
member of the class and initialize it to A, but then I realized that I
might not have to, I'm just not sure if it's a good idea or not.
It is legal. The temporary reference is returned to a temporary 'int'
object. The reference only survives until the end of the full expression
in which the call happens (in your case until the semicolon in the last
statement in 'main'), the temporary 'int' survives until the reference to
it goes away. Just don't do
int const & ri = t.get();
because right after that statement 'ri' is invalid.
Now, whether it's a good idea I am not sure. Why not simply return
a value instead of a reference?
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask