Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero-reinitializing a struct in C++

Tags:

A POD struct can be zero-initialized in C++11 as follows:

SomeStruct s{}; 

However, what do I do if I already have an instance of the struct and I want to re-initialize it to zeros? The following seems to work:

s = {}; 

Can someone point out the relevant standardese? I assume this is what is happening:

  1. A new zero-initialized instance gets created.
  2. The new instance is assigned to the existing instance, invoking the implicit assignment operator.
like image 925
TripShock Avatar asked Dec 23 '15 18:12

TripShock


People also ask

Does C initialize struct to 0?

You don't have to initialise every element of a structure, but can initialise only the first one; you don't need nested {} even to initialise aggregate members of a structure. Anything in C can be initialised with = 0 ; this initialises numeric elements to zero and pointers null.

Can struct have Initializers?

Using designated initializers, a C99 feature which allows you to name members to be initialized, structure members can be initialized in any order, and any (single) member of a union can be initialized. Designated initializers are described in detail in Designated initializers for aggregate types (C only).

How do you initialize a structure in C?

Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.


1 Answers

What you are looking for is in [expr.ass]

A braced-init-list may appear on the right-hand side of

  • an assignment to a scalar, in which case the initializer list shall have at most a single element. The meaning of x={v}, where T is the scalar type of the expression x, is that of x=T{v}. The meaning of x={} is x=T{}.
  • an assignment to an object of class type, in which case the initializer list is passed as the argument to the assignment operator function selected by overload resolution (13.5.3, 13.3).

So your guess is correct. The compiler may (can in C++17 and above) be able to optimize things away but you can think of it as create a zero-initialized temporary and pass it to the operator=.

like image 76
NathanOliver Avatar answered Oct 01 '22 17:10

NathanOliver