Using std::launder to “validate” non “pointer to object” pointer value since C++17

雨燕双飞 提交于 2019-12-03 11:15:12

问题


According to this answer, since C++17, even if a pointer has the right address and the right type dereferencing it can cause undefined behaviour.

 alignas(int) unsigned char buffer[2*sizeof(int)];
 auto p1=new(buffer) int{};
 auto p2=new(p1+1) int{};
 *(p1+1)=10; // UB since c++17

The reason is that the pointer value of p1+1 is a pointer past-the-end of an object. Can this example be brought back to defined behavior using std::launder:

 *std::launder(p1+1)=10; // still UB?  

Secondly, would it also be useful in this following case?

alignas(int) unsigned char buffer[3*sizeof(int)];
auto pi = new (buffer) int{};
auto pc = reinterpret_cast<unsigned char*>(pi);//not a "pointer to" an element of buffer 
                                               //since buffer[0] and *pc 
                                               //are not pointer interconvertible
//pc+2*sizeof(int) would be UB
auto pc_valid = std::launder(pc) //pc_valid is a pointer to an element of buffer
auto pc_valid2 = pc_valid+2*sizeof(int); //not UB thanks to std::launder
auto pi2 = new (pc_valid2) int{};

回答1:


No. The bytes constituting the int object p2 points to are not reachable through p1+1.


The "reachable" rule basically means that launder doesn't allow you to access storage you can't legally access via the original pointer. Since an opaque function may launder pointers as much as it wants, permitting this kind of shenanigans would substantially inhibit escape analysis.



来源:https://stackoverflow.com/questions/48067264/using-stdlaunder-to-validate-non-pointer-to-object-pointer-value-since-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!