Reputation: 1299
Is the following code correct from a C++ standard viewpoint?
Or do any of the cases outputting 0
in my example fail under certain circumstances?
struct Foo {
Foo() : k(), t{} {}
uint64_t i; //Uninitalized
uint64_t k;
uint64_t t;
};
int main(int argc, char ** argv) {
uint64_t i;
std::cout << i << std::endl; //Outputs garbage
uint64_t k = uint64_t();
std::cout << k << std::endl; //Outputs 0
uint64_t t = {};
std::cout << t << std::endl; //Outputs 0
//
Foo foo;
std::cout << foo.i << std::endl; //Outputs garbage
std::cout << foo.k << std::endl; //Outputs 0
std::cout << foo.t << std::endl; //Outputs 0
}
Upvotes: 1
Views: 195
Reputation: 12174
k()
and uint64_t k = uint64_t()
is value-initialized
that will then be zero:
(8.4) Otherwise, the object is zero-initialized.
t{}
and uint64_t t = {}
is list-initialized
that will default to zero.
Since Foo::i
and uint64_t i
is uninitialized, it will have an indeterminate value.
From dcl.init/12:
When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced ([expr.ass])
Upvotes: 3