Why specializing a type_trait could result in undefined behaviour?

前端 未结 2 473
故里飘歌
故里飘歌 2020-12-30 10:45

Discussion

According to the standard §20.10.2/1 Header synopsis [meta.type.synop]:

1

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 11:04

    Adding to Howard's answer (with an example).

    If users were allowed to specialize type traits they could lie (intentionally or by mistake) and the Standard Library could no longer assure that its behavior is correct.

    For instance, when an object of type std::vector is copied an optimization that popular implementations do is calling std::memcpy to copy all elements provided that T is trivially copy constructible. They might use std::is_trivially_copy_constructible to detect whether the optimization is safe or not. If not, then the implementation falls back to the safe but slower method which is looping through the elements and call T's copy constructor.

    Now, if one specializes std::is_trivially_copy_constructible for T = std::shared_ptr like this:

    namespace std {
        template <>
        class is_trivially_copy_constructible> : std::true_type {
        };
    }
    

    Then copying a std::vector> would be disastrous.

    This would not be the Standard Library implementation's fault but rather the specialization writer's. To some extend, that's what the quote provided by the OP says: "It's your fault, not mine."

提交回复
热议问题