【c/c++】打印uint8_t类型---nothrow---no-exceptions

1、通常打印uint8_t类型的时候,我们直接使用%u来打印。但是更加严谨的做法是使用%hhu来打印。详细说明参见cppreference
2、我们new之后,应该对指针进行判空,判断new是否执行成功

  • 很多时候我们会直接这样写 Xxx *obj = new Xxx();,但是这样写,当new执行失败后会抛出异常,而不是返回nullptr,所以后续的判空也就是无效的。
  • 正确的写法如下,应该给new标记nothrow,这样出错时就会返回nullptr
  • 详细参考cppreference
#include <iostream>
#include <string>

using namespace std;

class Xxx {
    int32_t mem1;
    string mem2;
};

int main()
{
    Xxx *obj = new(nothrow) Xxx();
    if (obj == nullptr) {
        cout << "some error" << endl;
        return -1;
    }
    return 0;
}

3、c++是默认使用异常机制的,当我们使用智能指针make_shared或者make_unique的时候不能直接通过判断其返回值,来判断make是否成功。而要使用try catch来处理异常。如下:

// make_shared.cpp
#include <iostream>
#include <string>
#include <memory>

using namespace std;

class Xxx {
    int32_t mem1;
    string mem2;
};

int main()
{
    try {
        shared_ptr<Xxx> ptr = make_shared<Xxx>();
    } catch(...) {
        cout << "make shared failed" << endl;
    }
    return 0;
}
  • 当然还有一种方法,那就是在编译的时候不使用异常机制:
    clang++ -fno-exceptions make_shared.cpp -o make_shared
  • 注意:不要同时使用上面两种方法,也就是不要同时使用try catchno-exceptions。否则会报如下错误:
make_shared.cpp:14:5: error: cannot use 'try' with exceptions disabled
    try {
    ^
1 error generated.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值