Is pointer arithmetic on allocated storage allowed since C++20?

女生的网名这么多〃 提交于 2020-07-04 11:59:49

问题


In the C++20 standard, it is said that array types are implicit lifetime type.

Does it mean that an array to a non implicit lifetime type can be implicitly created? The implicit creation of such an array would not cause creation of the array's elements?

Consider this case:

//implicit creation of an array of std::string 
//but not the std::string elements:
void * ptr = operator new(sizeof (std::string) * 10);
//use launder to get a "pointer to object" (which object?)
std::string * sptr = std::launder(static_cast<std::string*>(ptr));
//pointer arithmetic on not created array elements well defined?
new (sptr+1) std::string("second element");

Is this code not UB any more since C++20?


Maybe this way is better?

//implicit creation of an array of std::string 
//but not the std::string elements:
void * ptr = operator new(sizeof (std::string) * 10);
//use launder to get a "pointer to the array of 10 std::string" 
std::string (* sptr)[10] = std::launder(static_cast<std::string(*)[10]>(ptr));
//pointer arithmetic on an array is well defined
new (*sptr+1) std::string("second element");

回答1:


Does it means that an array to a non implicit lifetime type can be implicitly created?

Yes.

The implicit creation of such an array would not cause creation of the array's elements?

Yes.

This is what makes std::vector implementable in ordinary C++.



来源:https://stackoverflow.com/questions/60631224/is-pointer-arithmetic-on-allocated-storage-allowed-since-c20

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