自 C++20 以来,是否允许对分配的存储进行指针运算?

Oli*_*liv 13 c++ arrays lifetime dynamic-arrays c++20

在 C++20 标准中,说数组类型是隐式生命周期类型

这是否意味着可以隐式创建非隐式生命周期类型的数组?这种数组的隐式创建不会导致数组元素的创建?

考虑这个案例:

//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");
Run Code Online (Sandbox Code Playgroud)

从 C++20 开始,这段代码不再是 UB 了吗?


也许这种方式更好?

//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");
Run Code Online (Sandbox Code Playgroud)

T.C*_*.C. 5

这是否意味着可以隐式创建非隐式生命周期类型的数组?

是的。

隐式创建这样的数组不会导致创建数组的元素?

是的。

这就是在普通 C++ 中可以实现的原因std::vector