【C++】60 alignas 和[nodiscard]

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")]]
表示”不应该舍弃“,如果在实际使用的时候,舍弃了返回值,则会弹出警告。

  1. 一个被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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值