C++标准 — C++11特性补充
一、属性标识符
C++11中,引入了属性标识符的概念,用于修饰类型,对象,代码等。其表示方法为:
[[ attribute-list ]]
属性列表由 , 分割的属性组合而成。属性有四种表示方法:
- 简单属性,如 [[noreturn]]。
- 名称空间中的属性,如 [[gnu::unused]]。
- 带参的属性,如 [[deprecated(“because”)]]。
- 名称空间中的带参属性。
属性为各种由实现定义的语言扩展(例如 GNU 与 IBM 的语言扩展 attribute((…)),微软的语言扩展 __declspec() 等)提供了统一化的语法。
属性可用在 C++ 程序中的几乎所有位置,而且可应用于几乎所有事物:类型、变量、函数、名字、代码块、整个翻译单元,不过每个特定的属性都只在实现允许范围内有效:[[expect_true]] 可能是只能与 if,而非与类声明一同使用的属性,[[omp::parallel()]] 可能是应用到代码块或 for 循环,而非到类型 int 等的属性。
C++标准中定义的属性如下:
在C++参考手册中提供了几个例子:
[[gnu::always_inline]] [[gnu::hot]] [[gnu::const]] [[nodiscard]]
inline int f(); // declare f with four attributes
[[gnu::always_inline, gnu::const, gnu::hot, nodiscard]]
int f(); // same as above, but uses a single attr specifier that contains four attributes
// C++17:
[[using gnu:const, always_inline, hot]] [[nodiscard]]
int f [[gnu::always_inline]] (); // an attribute may appear in multiple specifiers
int f() {
return 0; }
我们不难看出这些非名称空间内的属性都是由C++标准提出的,要求编译器支持的;而名称空间内的属性,其作用结果取决各编译器。因此,属性是程序员指示编译器部分行为的工具。
二、编码转化
C++11中提供了用于字符转换的函数,位于头文件 <cuchar> 中:
以手册中 mbrtoc16 为例说明其用法。该函数声明为:
std::size_t mbrtoc16( char16_t* pc16,
const char* s,
std::size_t n,
std::mbstate_t* ps );
#include <iostream>
#include <iomanip>
#include <clocale>
#include <cstring>
#include <cwchar>
#include <cuchar>
using namespace std