Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

c++ - What is std::pair?

What is std::pair for, why would I use it, and what benefits does boost::compressed_pair bring?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...