简体   繁体   English

std::位集<n>实现导致大小被窃听</n>

[英]std::bitset<N> implementation causes size overheard

Seems like std::bitset<N> under the hood is an array of unsigned longs now, this means that there will be an (heavy?) overhead when N is small.看起来std::bitset<N>现在是一个unsigned longs数组,这意味着当 N 很小时会有(沉重的?)开销。 sizeof(std::bitset<8>) is 8 bytes ! sizeof(std::bitset<8>)8 bytes

Is there a reason why the type of underlying array itself is not a template parameter?底层数组本身的类型不是template参数是否有原因? Why does the implementation not use uint32_t/16_t/8_t when more appropriate?为什么实现在更合适的时候不使用uint32_t/16_t/8_t I do not see anything in the implementation that limits this?我在实施中没有看到任何限制这一点的东西吗?

I am guessing I am missing a particular reason but unsure how to look for it or maybe there is no reason at all?我猜我错过了一个特定的原因,但不确定如何寻找它或者根本没有原因? Since this is such a simple container I am not able to understand how the zero overhead principle of C++ seems to be avoided here.由于这是一个如此简单的container ,我无法理解这里似乎如何避免C++的零开销原则。

GCC Impl: https://gcc.gnu.org/onlinedocs/gcc-4.6.2/libstdc++/api/a00775_source.html GCC 实施: https://gcc.gnu.org/onlinedocs/gcc-4.6.2/libstdc++/api/a00775_source.html

I believe clang is similar (used sizeof to confirm)我相信 clang 是相似的(使用 sizeof 来确认)

I am not able to understand how the zero overhead principle of C++ seems to be avoided here.我无法理解这里似乎如何避免 C++ 的零开销原则。

The zero-overhead principle is a principle , not an absolute rule of C++.零开销原则是一个原则,不是C++的绝对规则。

Many people use std::vector in contexts where a compile-time fixed capacity would be useful.许多人在编译时固定容量有用的情况下使用std::vector Such a type could have only two pointers instead of three and thus be 50% smaller.这样的类型可以只有两个指针而不是三个,因此可以小 50%。 Many people use std::string in contexts where an immutable string would work just as well if not better;许多人使用std::string的上下文中,不可变字符串即使不是更好也同样有效; it would reduce the size of the string (ignoring SSO), as well as its complexity.它会减少字符串的大小(忽略 SSO),以及它的复杂性。 And so forth.等等。

These all represent inefficiencies relative to the standard type.这些都代表了相对于标准类型的低效率。 No standard library type can handle every possible usage scenario.没有标准库类型可以处理所有可能的使用场景。 The goal for such types is to be broadly useful, not perfect.这些类型的目标是广泛有用,而不是完美。

There is nothing preventing someone from writing a bitset-style type with the exact same interface which has a user-provided underlying type.没有什么可以阻止某人使用具有用户提供的基础类型的完全相同的接口编写位集样式类型。 But the standard has no such type.但是标准没有这种类型。

Indeed, there's nothing preventing implementations of bitset from choosing an underlying type based on the given number of bits.事实上,没有什么可以阻止bitset实现根据给定的位数选择底层类型。 Your implementation doesn't do that, but it could have.您的实现不会那样做,但它可以做到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM