Converting (void*) to std::vector

前端 未结 4 2062
难免孤独
难免孤独 2021-01-07 22:31

I have a (void*) buffer that I need to convert to std::vector before I can pass it on. Unfortunately, my C++ casting skills a

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-07 23:14

    You will need the length of the buffer. Once you do, we can do this:

    unsigned char *charBuf = (unsigned char*)voidBuf;
    /* create a vector by copying out the contents of charBuf */
    std::vector v(charBuf, charBuf + len);
    

    Okay, the comment got me started on why I did not use reinterpret_cast:

    • In C++, the C-style cast is a convenience function -- it asks the compiler to choose the safest and most portable form of conversion over the set of available cast operators.

    • The reinterpret_cast is implementation defined and should always be the last thing on your mind (and used when you are necessarily doing a non-portable thing knowingly).

    • The conversion between (unsigned doesn't change the type) char * and void * is portable (you could actually use static_cast if you are really picky).

    The problem with the C-style cast is: the added flexibility can cause heartaches when the pointer type changes.

    Note: I agree with the general convention of not casting as much as possible. However, without any source provided, this is the best I could do.

提交回复
热议问题