【问题标题】:boost compressed_pair and addresses of empty objects提升压缩对和空对象的地址
【发布时间】:2011-10-08 01:10:13
【问题描述】:

AFAIK,boost::compressed_pair 应该确保第一个和第二个成员的地址不同,同时它会发挥压缩对的魔力。上面写着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());

【问题讨论】:

    标签: c++ optimization boost


    【解决方案1】:

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

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

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

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

    boost 标题中的 cmets 表明,早些时候他们根本没有费心将同一个空类的两个不同实例放在压缩对中。相反,他们只存储了一个实例,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).
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 2011-06-28
      • 2019-11-23
      • 2017-04-16
      • 2016-07-26
      • 1970-01-01
      • 2011-03-25
      相关资源
      最近更新 更多