10

`folly::Indestructible`

 2 years ago
source link: https://blog.the-pans.com/folly-indestructible/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Menu

`folly::Indestructible`

Lu Pan | 07 May 2021 | 1 min read
`folly::Indestructible`

folly::Indestructible<T> is a class template that makes a static variable well, indestructible. Notice that it's meant for static variables in the Meyers Singleton pattern. If it's for heap allocated memory, it would just be called memory leak instead of "indestructible".

It boils down to making a destructor of T not actually destroy the underlying storage. The trick used by folly is to use union.

union Storage {
  T value;
  Storage() : value() {}
  ~Storage() {}
};
12345

From cppreference https://en.cppreference.com/w/cpp/language/destructor

For both user-defined or implicitly-defined destructors, after the body  of the destructor is executed, the compiler calls the destructors for  all non-static non-variant members of the class, in reverse order of  declaration, then it calls the destructors of all direct non-virtual  base classes

Because value is a variant member of the union, it won't be destructed if Storage s; is destructed.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK