1、alignas
参考:cppreference,博客
语法
- alignas( expression )
- alignas( type-id )
- alignas( pack … )
用于放在函数前面声明对齐方式的。
// every object of type struct_float will be aligned to alignof(float) boundary
// (usually 4):
struct alignas(float) struct_float
{
// your definition here
};
// every object of type sse_t will be aligned to 32-byte boundary:
struct alignas(32) sse_t
{
float sse_data[4];
};
// the array "cacheline" will be aligned to 64-byte boundary:
alignas(64) char cacheline[64];
2、alignof
返回一个类或者结构体的对其方式
语法
- alignof( type-id )
#include <iostream>
struct Foo
{
int i;
float f;
char c;
};
// Note: `alignas(alignof(long double))` below can be simplified to simply
// `alignas(long double)` if desired.
struct alignas(alignof(long double)) Foo2
{
// put your definition here
};
struct Empty {};
struct alignas(64) Empty64 {};
int main()
{
std::cout << "Alignment of" "\n"
"- char : " << alignof(char) << "\n"
"- pointer : " << alignof(int*) << "\n"
"- class Foo : " << alignof(Foo) << "\n"
"- class Foo2 : " << alignof(Foo2) << "\n"
"- empty class : " << alignof(Empty) << "\n"
"- empty class\n"
" with alignas(64): " << alignof(Empty64) << "\n";
}
3、[[nodiscard]]
nodiscard 是 C++17 引入的标记符。
语法
[[nodiscard]]
或者[[nodiscard("string")]]
。
表示”不应该舍弃“,如果在实际使用的时候,舍弃了返回值,则会弹出警告。
- 一个被nodiscard声明的函数被调用时,比如说:
[[nodiscard]] int func(){
return 1;}; // C++17
[[nodiscard("nodiscard_func_1")]] int func_1(){
return 2;}; // C++20
func(); // warning
func_1(); // warning
12345
编译器警告如下:
warning C4834: 放弃具有 "nodiscard" 属性的函数的返回值
warning C4858: 正在放弃返回值: nodiscard_func_1