☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

不可修改 std 命名空间

4.16 ID_stdNamespaceModified
目录 › next › previous

可以为用户定义的类型特化某些标准模板类,除此之外对 std 命名空间添加、修改甚至删除任何代码所导致的后果都是标准未定义的。

示例:

class MyType { .... };

namespace std
{
    size_t foo(const MyType& x);   // Non-compliant

    template <>
    struct hash<MyType> {
        size_t operator()(const MyType& x) const {
            return foo(x);
        }
    };
}

例中对 hash 标准模板类的特化是可被允许的,但在 std 命名空间中添加的 foo 函数是不被允许的。

应去掉 std 命名空间作用域声明,改为:

size_t foo(const MyType& x);   // OK

template <>
struct std::hash<MyType> {
    size_t operator()(const MyType& x) const {
        return foo(x);
    }
};

依据

ISO/IEC 14882:2011 17.6.4.2.1(1 2)-undefined ISO/IEC 14882:2017 20.5.4.2.1(1 2)-undefined

参考

SEI CERT DCL58-CPP
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.