If C++, if I write:
int i = 0;
int& r = i;
then are i
and r
exactly equivalent?
You are writing definitions here, with initializations. That means that you're refering to code like this:
void foo() {
int i = 0;
int& r = i;
}
but not
class bar {
int m_i;
int& m_r;
bar() : i(0), r(i) { }
};
The distinction matters. For instance, you can talk of the effects that m_i and m_r have on sizeof(bar)
but there's no equivalent sizeof(foo)
.
Now, when it comes to using i
and r
, you can distinguish a few different situations:
int anotherInt = r;
r = 5
int
, i.e. void baz(int); baz(r);
int&
, i.e. void baz(int&); baz(r);
template void baz(T); baz(r);
sizeof
, i.e. sizeof(r)
In these cases, they're identical. But there is one very important distinction:
std::string s = std::string("hello");
std::string const& cr = std::string("world");
The reference extends the lifetime of the temporary it's bound to, but the first line makes its a copy.