Can I reverse the process of array-to-pointer decay?

匿名 (未验证) 提交于 2019-12-03 03:12:02

问题:

Is it legal to cast a pointer to the first element of an array to a pointer to the entire array?

template<typename T, size_t N> void whatever(T(&)[N]) {     std::cout << N << '\n'; }  int main() {     int a[10];     int * p = a;     whatever(*(int(*)[10])(p));   // <-- legal? } 

This prints 10 on my compiler, but I'm not sure if the C++ standard allows it.

回答1:

No, it's not legal(as in it's Undefined Behavior). A pointer to the whole array is &a not p. Basically, you're casting one pointer to another. The standard describes all the allowed conversions and this one is not among them.



回答2:

I remember having concluded that

  • converting a pointer to the first element of a POD-struct into a pointer to the POD-struct
  • converting a pointer to one element of an array into a pointer to an array of size sufficiently small

are both well defined. But if the first conclusion was quite direct (i.e. there was a section in the standard saying so in quite plain words), the second took several steps (i.e. you needed to put together several part of the standard and draw a conclusion) and I've no time to redo the search now. If nobody gives citations one way or the other, I'll try to come back later with some.

Edit: I've not found my reasoning back. Currently all what I've is that under the assumption that reinterpret_cast gives the same result as the array decay, the round-trip from "pointer to array" to "pointer to first element" to "pointer to array" is guaranteed (per 5.2.10/7 in C++98) as the alignment requirement for an array can't be less strict than the alignment requirement for the element.



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