- noexcept的修饰和操作
#includevoid may_throw() { throw true; } auto non_block_throw = [] { may_throw(); }; void no_throw() noexcept { return; } auto block_throw = []() noexcept { no_throw(); }; int main() { std::cout << std::boolalpha << "may_throw() noexcept?" << noexcept(may_throw()) << std::endl << "no_throw() noexcept?" << noexcept(no_throw()) << std::endl << "lnay_throw() noexcept?" << noexcept(non_block_throw()) << std::endl << "lno_throw() noexcept?" << noexcept(block_throw()) << std::endl; return 0; }
输出结果:
may_throw() noexcept?false
no_throw() noexcept?true
lnay_throw() noexcept?false
lno_throw() noexcept?true
2.noexcept 修饰完一个函数之后能够起到封锁异常扩散的功效,如果内部产生异常,不会被外部捕捉到,会触发导致奔溃。
try {
may_throw();
}
catch (...) {
std::cout << "捕获异常" << std::endl;
}
3.原始字面量
#include#include int main() { std::string str = R"(C:\File\To\Path)"; std::cout << str << std::endl; return 0; }
4.自定义字面量
#include#include std::string operator"" _wow1(const char *wow1, size_t len) { return std::string(wow1) + "woooooooooow, amazing"; } std::string operator"" _wow2(unsigned long long i) { return std::to_string(i) + "woooooooooow, amazing"; } int main() { auto str = "abc"_wow1; auto num = 1_wow2; std::cout << str << std::endl; std::cout << num << std::endl; return 0; }
5.内存对齐
C++ 11 引入了两个新的关键字 alignof 和 alignas 来支持对内存对齐进行控制。 alignof 关键字能够获得一个与平台相关的 std::size_t 类型的值,用于查询该平台的对齐方式。 当然我们有时候并不满足于此,甚至希望自定定义结构的对齐方式,同样,C++ 11 还引入了 alignas 来重新修饰某个结构的对齐方式。我们来看两个例子:
#includestruct Storage { char a; int b; double c; long long d; }; struct alignas(std::max_align_t) AlignasStorage { char a; int b; double c; long long d; }; int main() { std::cout << alignof(Storage) << std::endl; std::cout << alignof(AlignasStorage) << std::endl; return 0; }
其中 std::max_align_t 要求每个标量类型的对齐方式严格一样,因此它几乎是最大标量没有差异, 进而大部分平台上得到的结果为 long double,因此我们这里得到的 AlignasStorage 的对齐要求是 8 或 16。



