std::map 属性 - C+标准要求?
你好,祝你有美好的一天。
标准 C++ std::map
- 如果 Value 具有以下属性,则它可以工作没有
operator=
或operator=
是私有的(并且std::map
不是 Value 的私有友元) 。 - 如果 Value 没有默认构造函数或默认构造函数是私有的(并且
std::map
不是 Value 的私有友元),那么它可以
工作我问 - 我被要求为内部使用 std::map 的类编写一个直接替代品。在过程中,事实证明该类应该在没有 operator=
的情况下工作(只要避免 map[key] = value;
)。我取消了 operator=
要求,但事实证明,使用 Value 的默认构造函数也会导致一些问题 (o_O),因为本应是 Value 的类没有默认构造函数。那么……这些标准属性是 std::map 的标准属性,还是原始类依赖于特定于实现/未定义的行为?我检查了“C++ 标准 - ANSI ISO IEC 14882 2003”,但找不到任何此类要求。我可能还可以取消“默认构造函数要求”(只要用户避免某些调用,例如为不存在的键调用 map[key]
),但我当然没有听说过此类属性之前的 std::map...
那么...您觉得怎么样?
Hello and good day to you.
Is this true (is it required by standard) that standard C++ std::map<Key, Value>
class is required to have following properties:
- It can work if Value has no
operator=
oroperator=
is private (andstd::map
is not a private friend of Value). - It can work if Value has no default constructor or default constructor is private (and
std::map
is not a private friend of Value)
Why I'm asking - I've been asked to write a drop-in replacement for the class that has been using std::map internally. IN process it turned out the class is supposed to work without operator=
(as long as you avoid map[key] = value;
). I nuked the operator=
requirment, but it turned out that using default constructors for Value also caused some problems (o_O), because class that was supposed to be Value had no default constructors. So... are those standard properties of std::map
, or was the original class relying on implementation-specific/undefined behavior? I checked "C++ Standard - ANSI ISO IEC 14882 2003", and I couldn't find any of such requirements. I can probably also nuke "default constructor requirement" (as long as user avoids certain calls, such as calling map[key]
for non-existent key), but I certainly haven't heard about such properties of std::map before...
So... what do you think?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据我对标准的阅读(C++11 中的 23.2.4 [associative.reqmts],但 C++03 中已经保留),
V
为DefaultConstructible
和V
为CopyAssignable
并不是实例化容器本身的强制要求,而只是为了使用它的一些操作。但是在 C++03 中,对于所有标准容器,
V
必须是CopyConstructible
。无条件地。在 C++11 中,这一要求被取消,因为可以使用新的emplace*
方法直接就地构建对象。From my reading of the Standard (23.2.4 [associative.reqmts] in C++11, but was already holding in C++03),
V
beingDefaultConstructible
andV
beingCopyAssignable
are not mandatory requirements for instantiating the container itself, but only to use some of its operations.However in C++03,
V
must beCopyConstructible
for all standard containers. Unconditionally. In C++11, this requirement is lifted because one can use the newemplace*
methods to build an object in place directly.