tags:

views:

66

answers:

3

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
}
+3  A: 

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 NULL because it must refer to somebody. Assigning to a reference assigns to the referencee.

Alexander Gessler
+1 and it also prevents code from trying to free the memory associated with the object.
Rob H
+2  A: 

Yes; ptrThis is just as good. Matter of style, I suppose. It does seem a bit redundant given what you've posted, but I'll give the original author the benefit of the doubt that it made sense in the context of the full example.

Terry Mahaffey
A: 

It doesn't have to do anything related to threads and as such cant interpret much from what code snippet which you have given

Yogesh Arora