Reinterpret casting with and without unsigned char * and char *

I am wondering if reinterpret_cast is needed in the function below. ITER_T could be char *, unsigned char *, std :: vector <unsigned char> iterator or something else like that. This does not seem to be offensive, but does casting affect how bytes are copied at all?

template<class ITER_T>
char *copy_binary(
  unsigned char length,
  const ITER_T& begin)
{
  // alloc_storage() returns a char*
  unsigned char* stg = reinterpret_cast<unsigned char*>(alloc_storage(length));
  std::copy(begin, begin + length, stg);
  return reinterpret_cast<char*>(stg);
}
+3
source share
4 answers

reinterpret_castsused for low-level tasks defined during implementation. According to the standard, it reinterpret_castscan be used for the following transformations (C ++ 03 5.2.10):

  • Pointer to integral type
  • Integral Type for Pointer
  • A pointer to a function can be converted to a pointer to a function of another type
  • - . , , .
  • A B, A B reinterpret_cast.

, reinterpret_cast , , char * unsigned char * .

static_cast , stg char *:

template<class ITER_T>
char *copy_binary(
  unsigned char length,
  const ITER_T& begin)
{
  // alloc_storage() returns a char*
  char* stg = alloc_storage(length);
  std::copy(begin, begin + length, stg);
  return stg;
}
+6

, , 4.7 (2), .

alloc_storage char *, "char" , , 4.7 (3), , , char * .

+1

- , .

char unsigned char (3.9.1 ++ Standard 0x n2800), . .

[3.9.1]... A char, char char ; .


[4.7]...

2 , , ( 2n, n - , ).

[: , ( ). -end note ]

3 , , ( ); .

( ) . , , .

template<class ITER_T>
char *copy_binary( unsigned char length, const ITER_T& begin)
{
  char* stg = alloc_storage(length);
  std::copy(begin, begin + length, stg);
  return stg;
}

reinterpret_cast :

[5.2.10.3] , reinterpret_cast - . [ , . -end note]

: .

+1

So, if I understood correctly, casting to an unsigned char is to provide an unsigned byte copy. But then you bring it back. The function looks a little quirky, what kind of context / reason for setting it up this way? A quick fix might be to replace all of this with memcpy () (but as commented out, do not use this on iterator objects) - otherwise just remove the redundant roles.

0
source

Source: https://habr.com/ru/post/1714340/


All Articles