I’ve came across the following code, ok, not exactly but close.
The point of interest is the second line in the (heavily abbreviated code).
Why does one have to intialize someReference ‘someReference’ ? Other then be able to use . operator instead of -> ?
ptrThis is just as good, no? (it’s inside the thread method, if that makes any difference)
// this line, why? SomeClass & someReference(*ptrThis); unsigned SomeClass::someThread(void *ptr) { SomeClass *ptrThis = reinterpret_cast<SomeClass*>(ptr); SomeClass & someReference(*ptrThis); // some other code }
References always need to be initialized when they’re declared (unless they’re external). They remain bound to one object during their whole lifetime. This ensures that a reference, unlike a normal pointer, can (theoretically) never be
NULLbecause it must refer to somebody. Assigning to a reference assigns to the referencee.