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 catch
和no-exceptions
。否则会报如下错误:
make_shared.cpp:14:5: error: cannot use 'try' with exceptions disabled
try {
^
1 error generated.