0

Let's say I have a char a; variable in C++, and I want to make it an unsigned char. Both datatype contains exactly one byte; the byte will stay the same when we do casting, so we are not really doing anything to the bytes.

However, I cannot change the type of variable a. If I declare a new variable unsigned char b = (unsigned char) a;, I am allocating memory for b (and using lots of memory if I have lots of such variables to cast), and I am doing unnecessary copying. How can I change the type of a without such copying?

Secondly, if I have std::vector<char> v; and I wish to cast it to std::vector<unsigned char>, what's the most efficient way to do so (without copying)? (Imagine a situation when you have char but some function takes unsigned char as its input.)

  • 4
    Generally speaking, when you feel the need to do a C-style casting like that, you should take that as a sign you're doing something wrong. What is the use-case? What problem is the cast supposed to solve? – Some programmer dude Mar 27 '22 at 14:29
  • You are allowed to just `reinterpret_cast` a `char*` to `unsigned char*` and access the characters through that. So there is no issue for this specific case. – user17732522 Mar 27 '22 at 14:32
  • _"if I have `std::vector v;` and I wish to cast it to `std::vector`, what's the most efficient way to do so (without copying)?_" - I suggested [this](https://stackoverflow.com/questions/62505019/assign-stdvectorstdbyte-to-stdvectorchar-without-copying-memory/62505567#62505567) to a similar question – Ted Lyngmo Mar 27 '22 at 14:32
  • 1
    If you need to pass a `vector` as a parameter to `void foo(vector&)` the code probably has a design flaw. – Eljay Mar 27 '22 at 14:38
  • 1
    Why not have your vector be `unsigned char` in the first place? – Taekahn Mar 27 '22 at 14:45
  • @Eljay See my comment at the end of the qiestion - sometimes one just cannot change the definition of every function (e.g. functions in a library). – Holding Arthur Mar 27 '22 at 15:05
  • That's why it's important to have good function interface from the very beginning. You can't cast `std::vector` into `std::vector` for distinct types `A` and `B`. – Evg Mar 27 '22 at 15:07
  • 2
    Does the library functions really take a `std::vector` as argument? Not iterators? Not a `unsigned char*` + length? – Ted Lyngmo Mar 27 '22 at 15:08
  • 2
    *sometimes one just cannot change the definition of every function* In those cases, one cannot avoid copying and transforming the data. – Eljay Mar 27 '22 at 15:26

0 Answers0