可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.