Is the usage of reinterpret_cast on a memcpy buffer UB?

后端 未结 1 1549
深忆病人
深忆病人 2021-02-15 14:39

Given the code

struct A {};

auto obj = new A;
std::vector buffer;
buffer.resize(sizeof(obj));
std::memcpy(buffer.data(), &obj, sizeof(o         


        
1条回答
  •  情深已故
    2021-02-15 15:26

    Yes, this code has undefined behavior. There is no object of type A* at the location pointed to by buffer.data(). All you did was copy the object representation of such a pointer into your vector [basic.types]/4. Since pointers are trivially copyable [basic.types]/9, if you were to copy back these bytes into an actual object of type A* and then delete the value of that, that would be well-defined [basic.types]/3. So this

    A* ptr;
    std::memcpy(&ptr, buffer.data(), sizeof(ptr));
    delete ptr;
    

    would be fine.

    Note that it is not the cast itself that invokes undefined behavior in your original example but your subsequent attempt to read the value of an object of type A* which does not exist where the pointer obtained via the cast points. All there exists where the pointer points is a sequence of objects of type unsigned char. The type A* is not a type that you may use to access the stored value of an object of type unsigned char [basic.lval]/8…

    0 讨论(0)
提交回复
热议问题