从C ++ 20开始是否允许对分配的存储进行指针算术运算? [英] Is pointer arithmetic on allocated storage allowed since C++20?
问题描述
在C ++ 20标准中,据说数组类型是隐式生存期类型.
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?
考虑这种情况:
//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");
自C ++ 20以来,此代码是否不再是UB?
Is this code not UB any more since 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 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");
推荐答案
这是否意味着可以隐式创建非隐式生命周期类型的数组?
Does it means 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?
是的
这就是std::vector
在普通C ++中可实现的原因.
This is what makes std::vector
implementable in ordinary C++.
这篇关于从C ++ 20开始是否允许对分配的存储进行指针算术运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!