提升compressed_pa​​ir和空对象的地址

时间:2011-10-08 01:10:14

标签: c++ optimization boost

AFAIK,boost::compressed_pair应该确保第一个和第二个memebrs的地址是不同的,同时它具有压缩该对的魔力。它如此表达here。看起来并非如此,并且它的行为在不同的编译器上是不同的。我正在使用boost v 1.47。我错过了什么?

struct E1 {};
struct E2 {};

boost::compressed_pair<E1, E2> diff_pair;
boost::compressed_pair<E1, E1> same_pair;

// clang++ and g++ 4.7 print the same address but VC2010 prints different addresses.
printf("different pairs = %p, %p\n", &diff_pair.first(), &diff_pair.second());

// clang++ and g++ 4.7 print different addresses but VC2010 prints the same address.
printf("different pairs = %p, %p\n", &same_pair.first(), &same_pair.second());

1 个答案:

答案 0 :(得分:7)

当类型不同并且一个或两个类型是空类时,子对象应该位于相同的地址(如果编译器可以关闭空基类优化),那就是压缩点对

当类型相同时,我认为标准第10章的注释适用:

  

基类子对象的大小可以为零(第9条);然而,两个   具有相同类类型且属于同一类的子对象   大多数派生对象不得分配在同一地址(5.10)。

因此,似乎需要编译器确保它们分配在不同的地址(并且VC10可能会出错)。

boost的标题中的注释表明,早先他们根本不打算在压缩对中放置同一个空类的两个不同实例。相反,他们只存储了一个实例,first()second()都返回了相同的对象。

   // 4    T1 == T2, T1 and T2 both empty
   //      Originally this did not store an instance of T2 at all
   //      but that led to problems beause it meant &x.first() == &x.second()
   //      which is not true for any other kind of pair, so now we store an instance
   //      of T2 just in case the user is relying on first() and second() returning
   //      different objects (albeit both empty).