C++17: Core language features (part 2)

Inline variables

For now, it’s possible to specify variables as inline.

For example:

it allows keep it only in a header, without adding to cpp static variable.

constexpr variables have implicit inline.

 

structured bindings

Structured bindings allow more easy to use tuples. For example in C++14 to get tuple results:

and in C++17, it will look like this:

Looks much simpler.

Also, structured bindings work with arrays:

Also, structured bindings work if class or struct have only non-static public members:

Reference to tuple object:

Using structured bindings inside for loops:

 

__has_include

Function macros which allow finding headers included in a compiler, because sometimes they can have a different path or be absent at all.

For example:

 

Attribute [[fallthrough]]

This attribute is used only inside switch statements, it used when fallthrough is expected and the compiler should not show warning about this.

For example:

 

Attribute [[nodiscard]]

This attribute is used when the value returned from function or method should not be discarded.

For example:

In this case, a compiler will show you the warning like this: discarding return value of function with ‘nodiscard‘ attribute.

To fix this, you need to check value which is marked as nodiscard.

For example:

 

Attribute [[maybe_unused]]

This attribute is used when warnings about unused need to be suppressed.

It can be used to suppress unused:

  • variables
  • typedefs
  • static data members
  • non-static data members
  • enums
  • functions

For example:

in this case, compiler can show a warning like this: unused variable ‘x’ [-Wunused-variable]

To suppress warning you need add this attribute:

 

std::launder

std::launder is used to get correct object represented by pointer within its lifetime.

For example:

std::launder protects memory and variables from compiler optimization, that way object pointed from std::launder is valid.

 

std::byte type 

std::byte was created to avoid issues with char, signed char, unsigned char. Because is char signed or unsigned, it’s compiler specific things.

std::byte is defined as:

std::byte can be used to access raw memory, but it’s not char type or integral byte. It’s just couple of bits.

Only bitwise operations are allowed.

For  example, this code will not work:

 

 

Leave a Reply

Your email address will not be published.