Das habe ich zusammengestellt von einem C++ -Kurs, dass bei uns jährlich im Forschungszentrum angeboten wird . Der Dozent ist Dr. Mohr und ich vertraue 100%, was er sagt. Da seine Erklärungen so KLAR sind, wollte ich die auch weitergeben .
JETZT IST ALLES KLAR! Viel Spass, Carmen
C++ introduces a new type: reference types. A reference type (sometimes also called an alias) serves as an alternative name for the object with which it has been initialized.
- a reference type acts like a special kind of pointer. Differences to pointer types:
-a reference must be initialized (must always refer to some object, i.e., no null reference)
-no need to test against 0
- once initialized, it cannot changed
- syntax to access reference object is the same as for "normal" objects
Code: Alles auswählen
/* references */
int i = 5, val = 10;
int &refVal = val;
int &otherRef; //error!
refVal++; //val/refVal now 11
refVal = i; //val/refval now 5
refVal++; //val/refVal now 6
Code: Alles auswählen
/* pointers */
int i = 5, val = 10;
int *ptrVal = &val;
int *otherPtr; //OK
(*ptrVal)++;
ptrVal = &i; //val still 11
(*ptrVal)++; // i now 6!
- The primary use of a reference type is as an parameter type or return type of a function.
They are rarely used directly.
Passing an object by value (default), to or from a function, invokes copy constructor.
And a constructor call will be followed by a destructor invocation
Code: Alles auswählen
class Coord { ... double x, y, z; };
class Triangle { ... Coord v1, v2, v3; };
Triangle return_triangle (Triangle t) { return t; }
- Eight (copy) constructors and eight destructors called
-
Solution: pass by reference (0 additional invocations)
Code: Alles auswählen
Triangle& return_triangle (const Triangle& t) { return t; }
-If possible, pass parameters by const reference to enable:
- processing of const objects
- automatic parameter conversions (non-const would change generated temporary only)
Recall:
do not return references to:
- local objects
- object allocated in function from free store
=>when new object is needed, return it by value