Re: warning C4238 : cast reference in void*

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance




Eric wrote:
Hi,

I want to pass a reference of an object as the parameter of a function.
This function takes an void*

Thats not a reference, its an address. And the trick is to cast the
receiving pointer. Note that a cast does *not* modify the casted
object. See below.


void foo(void* param)
{
...
}

int main()
{
CString szWord;

foo((void*) &szWord); //give C4238 warning : nonstandard extension
used : class rvalue used as lvalue
}

How can I solve this warning ?


void foo(void* param)
{
CString* ps = (CString*)param;
// use *ps
// or better
CString* psc = static_cast<CString*>(param);
// use *psc
}

int main()
{
CString word = "a string";
foo((void*)&word);
// or
foo(static_cast<void*>(&word));

return 0;
}

If you want foo() to take the pointer safely

void foo(void* const param) // a constant pointer to void
{
CString* ps = (CString*)param;
// param = 0; illegal
}

.



Relevant Pages

  • Re: back once again...
    ... reference to type ... a, signed char ... int dycObjectP(dyt obj); ... void dycBeginClass; ...
    (comp.lang.misc)
  • Re: pass by Reference/value ???
    ... > void foo ... this would be called "passing by reference". ... foo receives a local copy of s and any changes that it makes to s only ... Since s is a pointer, a variable storing the address of s is a pointer to ...
    (comp.lang.cpp)
  • Re: void types and how to use them efficiently?
    ... Where i use void as a generic object. ... this is also used for accessing info structs (per object, ... another approach is what is known as tagged references, ... to resolve the index to a pointer), it usually improves performance for many ...
    (comp.lang.c)
  • Re: basic question about references
    ... It expects a reference, ... not a pointer. ... void f; // a reference ... introduced for operator overloading because using ...
    (alt.comp.lang.learn.c-cpp)
  • Re: <OT> About pointer
    ... > void h{ ... > explicitly noting each place at which an underlying pointer mechanism ... passing "by reference" or passing a pointer ... > What does this program fragment print? ...
    (comp.lang.c)