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

不应连接不同前缀的字符串常量

11.6 ID_literal_hybridConcat
目录 › next › previous

连接不同前缀的字符串常量会导致标准未定义或由实现定义的行为。

示例:

typedef wchar_t S[];

S a = L"123" U"456";   // Non-compliant
S b = L"123" u"456";   // Non-compliant

C++03 规定宽字符串与窄字符串连接会导致未定义的行为;C++11 规定如果一个字符串有前缀另一个没有,结果以有前缀的为准,其他情况由实现定义或无法通过编译,如:

S x = L"123" "456";    // Undefined in C++03, a wide string in C++11
S y = L"123" U"456";   // Implementation defined in C++11
S z = L"123" u8"456";  // Ill-formed in C++11

C99 规定宽字符串与窄字符串连接的结果为宽字符串,C11 规定不同前缀的宽字符串连接结果由实现定义,如:

S u = L"123" "456";    // A wide string in C99
S v = L"123" U"456";   // Implementation defined in C11

为了提高可读性和可移植性,字符串前缀应保持一致:

S r = "123" L"456";    // Bad
S s = L"123" L"456";   // Good
S t = L"123" "456";    // Let it go?

对于有前缀和无前缀的字符串连接,在新的语言标准中均已有定义,审计工具不妨通过配置决定是否放过这种连接。

配置

allowPrefixedConcatUnprefixed: 是否允许有前缀和无前缀的字符串连接

依据

ISO/IEC 9899:1999 6.4.5(4) ISO/IEC 9899:2011 6.4.5(5)-implementation ISO/IEC 14882:2003 2.13.4(3)-undefined ISO/IEC 14882:2011 2.14.5(13)-implementation

参考

MISRA C++ 2008 2-13-5
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.