gpt4 book ai didi

c++ - boost 压缩对和空对象的地址

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:28:51 26 4
gpt4 key购买 nike

据我所知,boost::compressed_pair应该确保第一个和第二个 memebr 的地址不同,同时它会压缩这对。上面写着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());

最佳答案

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

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

A base class subobject may be of zero size (Clause 9); however, two subobjects that have the same class type and that belong to the same most derived object must not be allocated at the same address (5.10).

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

boost header 中的注释表明,之前他们根本没有费心将同一空类的两个不同实例放入压缩对中。相反,它们只存储了一个实例,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).

关于c++ - boost 压缩对和空对象的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7694158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com