Michael Safyan posted:
Dear members of comp.lang.c++,
I am a little bit confused about the differences between constant
references and values. I understand that it is faster to use a constant
reference ("const T&") than a value ("T") since the former does not
require copying whereas the latter does, is that correct?
Generalised answer: For large user-defined types, yes. For built-in types,
no.
In C++, references are "magical". The Standard says everything about how
they behave, but absolutely nothing about what they actually are.
In C, everything was passed by value, and everything was returned by value.
If you wanted to alter an object in the calling function, then you passed
its address. There was one other time, however, in C, where you passed the
object's address: when the object type was large and it would have been
more efficient to pass its address rather than passing the object by value.
As mysterious as references may be, they're still apart of our world, and
must obey the laws of our physics and so forth. If you have a scenario such
as:
struct PictureInfo {
unsigned width;
unsigned height;
unsigned colour_depth;
/* More members */
};
void Func(PictureInfo const &info)
{
/* Do stuff with the object */
}
Then the compiler will treat it as if you wrote:
void Func(PictureInfo const *const p)
For the most part, references are exactly like const pointers -- const
pointers which you don't have to dereference.
There's something special about "references to const" though. If you bind a
"reference to const" to an R-value, then an object is created which lives
until the reference goes out of scope. Writing the following:
{
int &r = 5;
}
is effectively like writing:
{
int const five = 5;
int &r = five;
}
Also, I un derstand that "const T&" allows for polymorphism whereas "T"
will generate code cuttting.
Indeed. In general though, you should always be passing user-defined
objects by reference to const, rather than by value.
On the former points, I am fairly confident... But I'm somewhat
confused on how the two influence conversions. For example, suppose I
define the following type:
class Real{
public:
Real(int)
Real(float);
Real(double);
Real(long double);
...
Real operator+(Real);
};
Can I now write the following?
Real x = 5.0;
Real y = x + 3;
//is above legal now if I don't define Real::operator+(int)?
Question to Physics teacher:
"I have an apple in my hand; if I let go of it, will gravity pull it to
the ground?"
Answer from Physics teacher:
"Why are you asking *me* when you can try compile it with your own
compiler?"
Now, suppose I change the declaration+definition of
Real::operator+(Real) to Real::operator+(const Real&), is the above
still legal? Or do I need to modify the above to the following?
Would it be legal if you passed its address? References are just a fancy
way of passing around addresses.
--
Frederick Gotham