What is std::pair?

前端 未结 10 1728
面向向阳花
面向向阳花 2020-12-12 19:07

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

10条回答
  •  抹茶落季
    2020-12-12 20:05

    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
    struct pair {
       FirstType first;
       SecondType second;
    };
    

    That means if either FirstType or SecondType is A, your pair has to be bigger than sizeof(int).

    But if you use compressed_pair, its generated code will look akin to:

     struct compressed_pair : private A {
        int second_;
        A first() { return *this; }
        int second() { return second_; }
     };
    

    And compressed_pair will only be as big as sizeof(int).

提交回复
热议问题