c++ - When do programmers use Empty Base Optimization (EBO) -


i reading empty base optimization(ebo). while reading, following questions popped in mind:

  1. what point of using empty class base class when it contributes nothing derived classes (neither functionality-wise, nor data-wise)?

  2. in this article, read this:

//s empty
class struct t : s
{
      int x;
};

[...]

notice didn’t lose data or code accuracy: when create standalone object of type s, object’s size still 1 (or more) before; when s used base class of class memory footprint shrink zero. realize impact of saving, imagine vector contains 125,000 objects. the ebo alone saves half megabyte of memory!

does mean if don't use "s" base class of "t", necessarily consume double of megabyte of memory? think, article compares 2 different scenarios don't think correct.

i know real scenario when ebo can proven useful.(means, in same scenario, necessarily @ loss if don't use ebo!).

please note if answer contains explanations :

the whole point empty class has non-zero size, when derived or deriving can have 0 size, i'm not asking that, know already. question is, why derive class empty class in first place? even if doesn't derive , writes class (without empty base), @ loss in way?

ebo important in context of policy based design, inherit privately multiple policy classes. if take example of thread safety policy, 1 imagine pseudo-code :

class mtsafepolicy { public:   void lock() { mutex_.lock(); }   void unlock() { mutex_.unlock(); }  private:   mutex mutex_; };  class mtunsafepolicy { public:   void lock() { /* no-op */ }   void unlock() { /* no-op */ } }; 

given policy based-design class such :

template<class threadsafetypolicy> class test : threadsafetypolicy {   /* ... */ }; 

using class mtunsafepolicy add no size overhead class test : it's perfect example of don't pay don't use.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -