c++关键字用法

本文介绍了C++中关于内存对齐的`alignas`关键字,展示了如何为结构体设置不同对齐方式,并通过实例演示了其对结构体大小的影响。同时,探讨了`alignof`操作符,用于获取类型所需的对齐要求。此外,还讨论了位运算符`&=`(and_eq)在位掩码操作中的应用,以及`is_integral`类型特性的使用,用于判断类型是否为整数类型。
摘要由CSDN通过智能技术生成

一:alignas 设置对其方式

#include <iostream>

using namespace std;
struct test1
{
    char a;
    int  b;
    double c;
};

struct alignas(8) test2
{
    char a;
    int b;
    double c;
};

struct alignas(16) test3
{
    char a;
    int b;
    double c;
};

struct alignas(32) test4
{
    char a;
    int b;
    double c;
};

struct alignas(64) test5
{
    char a;
    int b;
    double c;
};

int main()
{
    test1 t1;
    test2 t2;
    test3 t3;
    test4 t4;
    test5 t5;

    cout << "t1 size" << sizeof (t1) << '\n'
         << "t2 size" << sizeof (t2) << '\n'
         << "t3 size" << sizeof (t3) << '\n'
         << "t4 size" << sizeof (t4) << '\n'
         << "t5 size" << sizeof (t5) << '\n'
         << endl;
    return 0;
}

输出
t1 size16
t2 size16
t3 size16
t4 size32
t5 size64

二:alignof

返回由类型标识所指示的类型的任何实例所要求的对齐字节数

struct alignas(32) test4
{
    char a;
    int b;
    double c;
    double d;
    double e;
    double f;
    double g;

};

struct alignas(64)
{};

int main()
{
    std::cout << alignof(test4) << '\n';
    return 0;
}

输出32 和64

三:and_eq(&=)

#include <iostream>
#include <bitset>
int main()
{
    bitset<4> mask("1010");
    bitset<4> mink("1011");

    mask &= mink;
    std::cout << mask << '\n';
    return 0;
}

输出 :1010 (Qt中似乎不支持and_eq的写法)

四:is_integral 

is_integral 是一个模板,完整形式 is_integral<T>::value,用来判断传进来的参数T是否是int 类型

#include <iostream>

using namespace std;

int main()
{
    if(is_integral<char>::value)
        std::cout << "char is a int type\n";
    if(!is_integral<double>::value)
       std::cout << "double is not a int type" 

}

程序输出:

char is a int type
double is not a int type

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值