VC++ allows to use const types for STL containers. Why?

后端 未结 2 1494
你的背包
你的背包 2020-12-10 13:14

STL containers require the stored values to be copy constructible and assignable. const T is obviously not an assignable type for any T, but I tried to use it (just being cu

2条回答
  •  误落风尘
    2020-12-10 14:01

    This is not a bug in the implementation as others have suggested.

    Violating the requirements of a C++ Standard Library facility does not render your program ill-formed, it yields undefined behavior.

    You have violated the requirement that the value type stored in a container must be copy constructible and assignable (const types are not assignable, obviously), so your program exhibits undefined behavior.

    The applicable language from the C++ Standard can be found in C++03 17.4.3.6 [lib.res.on.functions]:

    In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C++ Standard Library depends on components supplied by a C++ program. If these components do not meet their requirements, the Standard places no requirements on the implementation.

    In particular, the effects are undefined in the following cases:

    ...

    • for types used as template arguments when instantiating a template component, if the operations on the type do not implement the semantics of the applicable Requirements subclause.

    The Visual C++ Standard Library implementation may do anything with this code, including silently removing or ignoring the const-qualification, and it is still standards-conforming.

提交回复
热议问题