'className SerialNow = *((className*)ptr); vs className &SerialNow = *((className*)ptr);

What is difference between using or not reference when casting pointer to object?

void someClass::method() {
    xTaskCreatePinnedToCore(someTaskHandler,"SerialNowTaskTX",XT_STACK_MIN_SIZE*3,this,4,&taskHandleTX,0); // passing 'this' to task handler
}

void someTaskHandler(void *p) {
    SerialNow_ SerialNow = *((SerialNow_*)p); // compile but not working properly
    SerialNow_ &SerialNow = *((SerialNow_*)p); // compile and working
    SerialNow_ *SerialNow = ((SerialNow_*)p); // compile and working but I prefer . over ->
    int A = SerialNow.somethingA;
    SerialNow.somethingB();

    while(1) {
    
    }

    vTaskDelete(NULL);
}


Solution 1:[1]

Case 1

Here we consider the statement:

SerialNow_ SerialNow = *((SerialNow_*)p);

Here the void* p is casted(using explicit type conversion) to SerialNow_*. Next, that resulting SerialNow_* is dereferenced using the *operator resulting in an object of type SerialNow_.

Finally, that resulting SerialNow_ object is used as an initializer to initialize the object named SerialNow on the left hand side. The newly initialized object SerialNow is a copy of the original object. This means that if you make changes to SerialNow it won't affect the original object pointed to by p.

Case 2

Here we consider the statement:

SerialNow_ &SerialNow = *((SerialNow_*)p); 

In this case, most of the process is same as case 1 except that this time SerialNow is an alias for the resulting object. This is different from case one only in that in case 1 the object SerialNow on the left hand side was a copy of the original object while here the SerialNow on the left hand side is an lvalue reference to the original object. This means that if you make changes to SerialNow it will affect the original object pointed to by p.

Case 3

Here we consider the statement:

SerialNow_ *SerialNow = ((SerialNow_*)p);

Here the void* p is casted to SerialNow_*. But that resulting pointer is not dereferenced unlike case 1 and case 2. Thus, here the object named SerialNow on the left hand side is initialized from the pointer resulting from the explicit type conversion.

Moreover, SerialNow is a copy of the pointer resulting from the explicit type conversion..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1