This lesson explains the concept of "postblit".

We'll cover the following

What is “postblit”?

Copying is constructing a new object from an existing one. Copying involves two steps:

  1. Copying the members of the existing object to the new object bit-by-bit. This step is called blit, short for block transfer.
  2. The second step is making further adjustments to the new object after the block transfer. This step is called postblit.

The first step is handled automatically by the compiler, which copies the members of the existing object to the members of the new object:

auto returnTripDuration = tripDuration; // copying

Do not confuse copying with assignment. The auto keyword above is an indication that a new object is being defined.

The actual type name could have been spelled out instead of auto. The keyword auto could have been used instead of the actual type name.

For an operation to be an assignment, the object on the left-hand side must be an existing object. For example, assuming that returnTripDuration has already been defined:

returnTripDuration = tripDuration; // assignment (see below)

Sometimes, it is necessary to make adjustments to the members of the new object after the automatic blit. These operations are defined in the postblit function of the struct.

Since postblit is about object construction, the name of the postblit is also this. To distinguish it from the other constructors, the parameter list of a postblit contains the keyword this:

this(this) {
    // ...

You have defined a Student type in the structs chapter, which had a problem about copying objects of that type:

struct Student {
    int number;
    int[] grades;

Being a slice, the grades member of that struct is a reference type. The consequence of copying a Student object is that the grades members of both the original and the copy provide access to the same actual array elements of type int. As a result, the effect of modifying a grade through one of these objects is seen through the other object as well:

Get hands-on with 1000+ tech skills courses.