gpt4 book ai didi

c++ - 关于STL中的非相等分配器

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:42 25 4
gpt4 key购买 nike

我正在阅读 Scott Meyers 在 Effective STL 中关于 C++ 分配器的第 10 条。

Standard says that an implementation of the STL is permitted to assume that all allocator objects of the same type are equivalent and always compare equal.

That's all well and good, but the more you think about it. the more you'll realize just how draconian a restriction it is that STL implementations may assume that allocators of the same type are equivalent. It means that portable allocator objects — allocators that will function correctly under different STL implementations — may not have state. Let's be explicit about this: it means that portable allocators may not have any nonstatic data members, at least not any that affect their behavior. None. Nada. That means, for example, you can't have one SpecialAllocator that allocates from one heap and a different SpecialAllocator that allocates from a different heap. Such allocators wouldn't be equivalent, and STL implementations exist where attempts to use both allocators could lead to corrupt runtime data structures.

In fairness to the Standardization Committee, I should point out that it included the following statement immediately after the text that permits STL implementers to assume that allocators of the same type are equivalent:

Implementors are encouraged to supply libraries that ... support non-equal instances. In such implementations. ... the semantics of containers and algorithms when allocator instances compare non-equal are implementation-defined.

This is a lovely sentiment, but as a user of the STL who is considering the development of a custom allocator with state, it offers you next to nothing. You can take advantage of this statement only if (1) you know that the STL implementations you are using support inequivalent allocators, (2) you are willing to delve into their documentation to determine whether the implementation-defined behavior of "non-equal" allocators is acceptable to you, and

(3) you're not concerned about porting your code to STL implementations that may take advantage of the latitude expressly extended to them by the Standard. In short, this paragraph — paragraph 5 of section 20.1.5. for those who insist on knowing — is the Standard's "1 have a dream" speech for allocators. Until that dream becomes common reality, programmers concerned about portability will limit themselves to custom allocators with no state.

我对以上段落的问题是

  1. 作者所说的不等价或不等价分配器是什么意思?

  2. 上面文字的最后一段,即第 3 点简单来说是什么意思?

最佳答案

该信息已过时。 C++11 及更高版本支持有状态分配器。

如果您正在编写需要自定义分配器、不需要 C++11 并且支持针对未知/未指定的标准库进行构建的 C++ 库,那么您从 Effective C++ 中发布的引述才值得关注。初步估计,没有人再这样做了。以前这样做的人通常有自己的“增强型”标准库实现来支持状态分配器,例如 EASTL 或 BDESTL。

关于c++ - 关于STL中的非相等分配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47634572/

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