考虑到整个 C++11 标准,任何符合要求的实现是否有可能成功下面的第一个断言但失败了后者?
#include <cassert>
int main(int, char**)
{
const int I = 5, J = 4, K = 3;
const int N = I * J * K;
int arr1d[N] = {0};
int (&arr3d)[I][J][K] = reinterpret_cast<int (&)[I][J][K]>(arr1d);
assert(static_cast<void*>(arr1d) ==
static_cast<void*>(arr3d)); // is this necessary?
arr3d[3][2][1] = 1;
assert(arr1d[3 * (J * K) + 2 * K + 1] == 1); // UB?
}
如果不是,这在技术上是否是 UB,如果第一个断言被删除,答案是否会改变(reinterpret_cast 是否保证在这里保留地址?)?另外,如果 reshape 是在相反的方向(3d 到 1d)或从 6x35 阵列到 10x21 阵列进行的?
编辑:如果答案是由于 reinterpret_cast 而导致这是 UB,是否还有其他一些严格兼容的 reshape 方式(例如,通过 static_cast 到/从中间 void *)?
最佳答案
2021-03-20 更新:
同样的问题是 asked on Reddit最近有人指出我的原始答案有缺陷,因为它没有考虑到这个 aliasing rule :
If a program attempts to access the stored value of an object through a glvalue whose type is not similar to one of the following types the behavior is undefined:
- the dynamic type of the object,
- a type that is the signed or unsigned type corresponding to the dynamic type of the object, or
- a char, unsigned char, or std::byte type.
根据 similarity 的规则,这两种数组类型在上述任何情况下都不相似,因此通过 3D 数组访问 1D 数组在技术上是未定义的行为。 (这绝对是其中一种情况,在实践中,它几乎可以肯定适用于大多数编译器/目标)
请注意,原始答案中的引用是指较旧的 C++11 草案标准
reinterpret_cast引用文献标准规定 T1 类型的左值可以是reinterpret_cast对 T2 的引用如果指向 T1 的指针可以是reinterpret_cast指向 T2 的指针(§5.2.10/11):
An lvalue expression of type
T1can be cast to the type “reference toT2” if an expression of type “pointer toT1” can be explicitly converted to the type “pointer toT2” using a reinterpret_cast.
所以我们需要确定 int(*)[N]可以转换为 int(*)[I][J][K] .
reinterpret_cast指针指向 T1 的指针可以是reinterpret_cast指向 T2 的指针如果两者都是 T1和 T2是标准布局类型和 T2没有比 T1 更严格的对齐要求(§5.2.10/7):
When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”, the result is
static_cast<cv T2*>(static_cast<cv void*>(v))if bothT1andT2are standard-layout types (3.9) and the alignment requirements ofT2are no stricter than those ofT1, or if either type is void.
是 int[N]和 int[I][J][K]标准布局类型?
int是标量类型,标量类型的数组被视为标准布局类型(第 3.9/9 节)。
Scalar types, standard-layout class types (Clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called standard-layout types.
是否 int[I][J][K]没有比 int[N] 更严格的对齐要求.
alignof 的结果运算符给出完整对象类型的对齐要求(第 3.11/2 节)。
The result of the
alignofoperator reflects the alignment requirement of the type in the complete-object case.
由于这里的两个数组不是任何其他对象的子对象,它们是完整的对象。申请alignof到数组给出元素类型的对齐要求(§5.3.6/3):
When
alignofis applied to an array type, the result shall be the alignment of the element type.
所以这两种数组类型具有相同的对齐要求。
这使得 reinterpret_cast有效且等价于:
int (&arr3d)[I][J][K] = *reinterpret_cast<int (*)[I][J][K]>(&arr1d);
在哪里 *和 &是内置运算符,则相当于:
int (&arr3d)[I][J][K] = *static_cast<int (*)[I][J][K]>(static_cast<void*>(&arr1d));
static_cast通过void* static_cast至void*标准转换(§4.10/2)允许:
A prvalue of type “pointer to cv
T,” whereTis an object type, can be converted to a prvalue of type “pointer to cv void”. The result of converting a “pointer to cvT” to a “pointer to cv void” points to the start of the storage location where the object of typeTresides, as if the object is a most derived object (1.8) of typeT(that is, not a base class subobject).
static_cast至int(*)[I][J][K]然后被允许(§5.2.9/13):
A prvalue of type “pointer to cv1
void” can be converted to a prvalue of type “pointer to cv2T,” whereTis an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1.
所以转换没问题!但是我们可以通过新的数组引用访问对象吗?
对像 arr3d[E2] 这样的数组执行数组下标相当于 *((E1)+(E2)) (§5.2.1/1)。让我们考虑以下数组下标:
arr3d[3][2][1]
首先,arr3d[3]相当于 *((arr3d)+(3)) .左值 arr3d进行数组到指针的转换,得到 int(*)[2][1] .不要求底层数组必须是正确的类型才能进行此转换。然后访问指针值(第 3.10 节很好),然后将值 3 添加到它。这种指针算法也很好(§5.7/5):
If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.
这个 this 指针被取消引用以给出 int[2][1] .这对接下来的两个下标进行相同的过程,产生最终的 int在适当的数组索引处的左值。由于 * 的结果,它是一个左值(§5.3.1/1):
The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points.
这样就可以访问实际的 int对象通过这个左值,因为左值的类型是 int太(§3.10/10):
If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:
- the dynamic type of the object
- [...]
所以除非我错过了什么。我会说这个程序定义明确。
关于c++ - 将一维数组 reshape 为多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15283523/
我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代
我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby数组,我们在StackOverflow上找到一
我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife
我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat
我正在尝试在Ruby中制作一个cli应用程序,它接受一个给定的数组,然后将其显示为一个列表,我可以使用箭头键浏览它。我觉得我已经在Ruby中看到一个库已经这样做了,但我记不起它的名字了。我正在尝试对soundcloud2000中的代码进行逆向工程做类似的事情,但他的代码与SoundcloudAPI的使用紧密耦合。我知道cursesgem,我正在考虑更抽象的东西。广告有没有人见过可以做到这一点的库或一些概念证明的Ruby代码可以做到这一点? 最佳答案 我不知道这是否是您正在寻找的,但也许您可以使用我的想法。由于我没有关于您要完成的工作
我使用Ember作为我的前端和GrapeAPI来为我的API提供服务。前端发送类似:{"service"=>{"name"=>"Name","duration"=>"30","user"=>nil,"organization"=>"org","category"=>nil,"description"=>"description","disabled"=>true,"color"=>nil,"availabilities"=>[{"day"=>"Saturday","enabled"=>false,"timeSlots"=>[{"startAt"=>"09:00AM","endAt"=>
我正在尝试按0-9和a-z的顺序创建数字和字母列表。我有一组值value_array=['0','1','2','3','4','5','6','7','8','9','a','b','光盘','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','','u','v','w','x','y','z']和一个组合列表的数组,按顺序,这些数字可以产生x个字符,比方说三个list_array=[]和一个当前字母和数字组合的数组(在将它插入列表数组之前我会把它变成一个字符串,]current_combo['0','0','0']