Mixing a temporary object

Look at this piece of code

struct S{ int i; int j;}; int main() { assert(S().i == S().j) // is it guaranteed ? } 

Why?

+7
c ++ temporary
source share
3 answers

is he guaranteed?

Yes, it is guaranteed. The values โ€‹โ€‹of S().i and S().j will be 0 . () means initializing the value. (this means that i and j will be initialized to zeros because S is a class without a custom constructor by default)

+10
source share

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

Objects with static storage duration (3.7.1) must be initialized with zeros (8.5) before any other initialization takes place.

So this is true, since both variables are initialized to zero.

0
source share

Technically, yes. They will be initialized to 0 (at least as part of a non-debug build for most compilers. The Visual Studio compiler usually initializes uninitialized variables for a specific template in debug builds) .

However, if you were sitting in a code review, do not be surprised if you screamed so that your variables would not be initialized explicitly.

-one
source share

All Articles