18 Ağustos 2020 Salı

no_unique_address - C++20

Giriş
Açıklaması şöyle. Empty Base Optimization kalıtımı mecbur kılıyordu.  no_unique_address kullanarak kalıtımı mecburiyetinden kurtuluyoruz.
Applies to the name being declared in the declaration of a non-static data member that's not a bit field.

Indicates that this data member need not have an address distinct from all other non-static data members of its class. This means that if the member has an empty type (e.g. stateless Allocator), the compiler may optimise it to occupy no space, just like if it were an empty base. If the member is not empty, any tail padding in it may be also reused to store other data members.
Örnek
Elimizde şöyle bir kod olsun. X'in büyüklüğü 5, Y'nin büyüklüğü 4, Z''nin büyüklüğü 2, W'nin büyüklüğü 2 çıkabilir.
#include <iostream>
 
struct Empty {}; // empty class
 
struct X {
  int i;
  Empty e;
};
 
struct Y {
  int i;
  [[no_unique_address]] Empty e;
};
 
struct Z {
  char c;
  [[no_unique_address]] Empty e1, e2;
};
 
struct W {
  char c[2];
  [[no_unique_address]] Empty e1, e2;
};
Örnek
Şöyle yaparız
template<class T, class Deleter>
class unique_ptr {
  T* pointer = nullptr;
  // Now, if Deleter is empty it won't take up any space in the class
  [[no_unique_address]] Deleter deleter;
public:
  // STuff...

Hiç yorum yok:

Yorum Gönder