compressed_pair
uses some template trickery to save space. In C++, an object (small o) can not have the same address as a different object.
So even if you have
struct A { };
A
's size will not be 0, because then:
A a1;
A a2;
&a1 == &a2;
would hold, which is not allowed.
But many compilers will do what is called the "empty base class optimization":
struct A { };
struct B { int x; };
struct C : public A { int x; };
Here, it is fine for B
and C
to have the same size, even if sizeof(A)
can't be zero.
So boost::compressed_pair
takes advantage of this optimization and will, where possible, inherit from one or the other of the types in the pair if it is empty.
So a std::pair
might look like (I've elided a good deal, ctors etc.):
template<typename FirstType, typename SecondType>
struct pair {
FirstType first;
SecondType second;
};
That means if either FirstType
or SecondType
is A
, your pair<A, int>
has to be bigger than sizeof(int)
.
But if you use compressed_pair
, its generated code will look akin to:
struct compressed_pair<A,int> : private A {
int second_;
A first() { return *this; }
int second() { return second_; }
};
And compressed_pair<A,int>
will only be as big as sizeof(int).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…