Does int() return 0 or an arbitrary value?

北城余情 提交于 2019-12-24 13:43:04

问题


Consider this code:

template <typename T>
void f()
{T x = T();}

When T = int, is x equal to 0 or to an arbitrary value?

Bonus question: and consequently, are arrays (both T[N] and std::array<T, N>) the only types where such a syntax may leave contents with arbitrary values.


回答1:


T() gives value initialization, which gives zero-initialization for a type other than a class, union or array. (§8.5/7 bullet 3): "otherwise, the object is zero-initialized." For an array, each element of the array is value initialized.

For an array, the content will be of an arbitrary value if it's auto storage class, but zero initialized if it's static storage class -- i.e., global (assuming, of course, that you don't specify any initialization).




回答2:


Regarding your first question, it is called value-initialization, and is well-covered in the standard (C++11 § 8.5 covers initialization in detail, with the specifics on () initialization and how it eventually leads to zero-initialization, starting with 8.5/16 (covers ()), which leads to 8.5/7 (value-initialization), and finally 8.5/5 (zero-initialization).

Regarding std::array<T,N>, if T is a class-type the constructors will fire for each element (user-provided or default if none are provided by the user). If default construction happens default-initialization will fire (which isn't very exciting). By the standard (8.5/6), each element is default-initialized. For T that is not a class type this is effectively the same as T ar[N]; which as you have pointed out, is indeterminate as well (because it is default initialized, which by the standard "no initialization is performed.".

Finally, if static storage is declared for your fixed array of non-class-type, it resides in zero-filled memory on inception. For automatic storage, its back to "no initialization is performed." as your end-game.

I hope i didn't miss something (and I know i'll hear it if I did). There are lots of interesting questions on SO that cover areas like this. If I get a chance I'll link a few.



来源:https://stackoverflow.com/questions/18295614/does-int-return-0-or-an-arbitrary-value

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