For the following definition of
const vector3F operator*(const vector3F &v, float s);
There are two const
, what are their respective usages?
The const-reference in the argument means that you don't change v
, so you can pass constant vectors (and temporaries!) to the function. That's a Good Thing.
The constant by-value return is sort of a gimmick. It prevents you from writing things like this:
vector3F v = get_vector();
vector3F w = v;
(v * 1.5) = w; // outch! Cannot assign to constant, though, so we're good.
Returning by-value as constant is problematic, though, since it interferes with C++11's rvalue references and move semantics:
move_me(v * 1.5); // cannot bind to `vector3F &&` :-(
Because of that, and because an abuse like the one I showed above is fairly unlikely to happen by accident, it's probably best to return by value only as non-constant.
The first const indicates that the return value is constant and can not be altered (which, by the way, is a bad idea for the multiplication operator):
const Vector3F v = myvector*100.0;
v.x = 0; // error: the vector is constant and can not be altered
The second const indicates that the argument "v" is constant:
const vector3F operator*(const vector3F &v, float s)
{
v.x = 0; // error: "v" is constant
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.