开发者

Temporary Object confusion

开发者 https://www.devze.com 2023-01-29 12:29 出处:网络
Have a look at this code snippet struct S{ int i; int j;}; int main() { assert(S().i ==S().j) // 开发者_JAVA技巧is it guaranteed ?

Have a look at this code snippet

struct S{ int i; int j;};

int main()
{
   assert(S().i ==  S().j) // 开发者_JAVA技巧is it guaranteed ?
}

Why?


is it guaranteed ?

Yes it is guaranteed. The values of S().i and S().j would be 0. () implies value initialization. (that means i and j would be zero-initialized because S is a class without a user defined default constructor)


From C++ Standard ISO/IEC 14882:2003(E) point 3.6.2

Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place.

So this is valid as both variables are zero-initialized.


Technically, yes. They will be initialized to 0 (at least under a non-debug build for most compilers. Visual Studio's compiler will usually initialize uninitialized variables to a specific pattern in debug builds).

However, if you were sitting in a code review, don't be surprised if you get yelled at for not explicitly initializing your variables.

0

精彩评论

暂无评论...
验证码 换一张
取 消