LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   converting c code to c++ causes an type error (https://www.linuxquestions.org/questions/programming-9/converting-c-code-to-c-causes-an-type-error-797771/)

knobby67 03-25-2010 06:11 AM

converting c code to c++ causes an type error
 
Hi all,
hope someone can help me out with this. I'm a C / assembler programmer so am not use to C++, which I need to use. Basically I'm using my own versions of memcpy, but for long and int rather than char. It's for fast graphics. So I have a char array which I copy to another array. But I copy as either longs or ints, much faster. for example
Code:

void * fastmemcpysprite (void *destaddr, void const *srcaddr, size_t len)
{

  register int *dest = destaddr;
  register int const *src = srcaddr;

  len /= 4;
  while (len-- > 0)  *dest++ = *src++;
  return destaddr;
}

but under C++ the int *dest *src says they should be void const void.
I tried changing my voids but of course this the causes errors as I'm passing an array of chars. I've Google but the couple of c++ examples seem to do it in exactly the same way I do :S

Can anyone point me in the right direction.

JohnGraham 03-25-2010 06:25 AM

Quote:

Originally Posted by knobby67 (Post 3911587)
but under C++ the int *dest *src says they should be void const void.

In C++, you can't (shouldn't be able to) cast from void* implicitly - you just need to make it explicit:

Code:

  register int *dest = (int*) destaddr;
  register int const *src = (int const *)srcaddr;

John G

P.S. Or, even better, use "static_cast<int*>(destaddr)" instead of "(int*)destaddr", which'll just make the cast more visible and easier to search for.

knobby67 03-25-2010 07:02 AM

Thanks that solves that problem, but then a whole host of others open up.
I might be gone some time :D

johnsfine 03-25-2010 08:02 AM

Quote:

Originally Posted by JohnGraham (Post 3911599)
even better, use "static_cast<int*>(destaddr)" instead of "(int*)destaddr", which'll just make the cast more visible and easier to search for.

I think reinterpret_cast<int*>(destaddr) is a better fit for the meaning that cast.

A static_cast implies there may be some change to the pointer value that the compiler should know how to do. For example, you may static_cast to a pointer to a derived class. The programmer is responsible for being sure that the pointer you cast from really is a base class subobject of the specified derived class. But the compiler is responsible for adjusting any offsets in case that base class subobject is not the physically first component of the derived class.

By contrast, a reinterpret_cast strictly means the exact same pointer that pointed to one of those now points top one of these.


All times are GMT -5. The time now is 03:59 AM.