Range-Based for循环
int x2[]{1, 2, 3, 4, 6};
for (auto i:x2)
{
cout << i << endl;
}
{
//等同上面for循环
for (auto _pos = begin(x2), _end = end(x2); _pos!=_end; ++_pos)
{
// auto decl = *_pos;
cout << *_pos << endl;
}
//class template std::initializer_lis<>提供了begin()和end()
//所以可以如下for循环
for (auto tmp: {1,2,3,4,5,7})
{
cout << tmp << endl;
}
}
//避免下面的元素调用了构造和析构函数,下面的for循环采用const reference
template<typename T>
void printElements(const T &coll)
{
for (const auto &elem : coll)//const reference
{
std::cout << elem << std::endl;
}
}
Move语义和Rvalue Reference
待补充,对实现理解的一知半解
新式字符串字面常量(String Literal)
Raw String Literal
语法:R"delim(....)delim"
其中delim是一个字符序列,最多16个基本字符,不可以包含反斜线、空格、小括号。
其允许我们定义字符序列(character sequence)
,从而避免书写很多的转移字符。
std::string x3(R"(\\n)");
std::string x4("\\\\n");//同上
std::string rawStr = R"(\\n)";
std::string rawStr = R"nc(a\
b\nc()"
)nc";
cout << rawStr << endl;
//完整语法书输出
cout << "===========" << endl;
/*
a\
b\nc()"
===========
*/
编码的String Literal
- u8 以UTF-8编定的某个字符起头,字符类型为const char
- u 定义一个string literal,带着类型为char16_t
- U定义一个string literal,带着类型为char32_t
- L定义一个wide string literal,带着类型为wchar_t的字符
- Raw string开头的那个R的前面还可以放置一个编码前缀
关键字noexcept
用来指明某个函数无法——或不打算——抛出异常。例如:
void foo() noexcept;//如果foo()有异常未被处理或者抛出异常,则程序会被终止
//然后std::terminate()被调用并默认调用std::abort()
关键字constexpr
不是很了解用法,需要后续补充
//constexpr 用于让表达式在编译期通过检查
constexpr int square(int x)
{
return x*x;
}
float a[square(9)];//constexpr用来在这里使得数组通过编译期运算
# main()定义式
c++标准中定义“正确且具有移植性”的main()如下所示,c++中隐式的定义了一个return 0;
int main()
{
}
和
int main(int argc, char * argv[])
{
}
异常Execption
一下示范如何使用一个泛型函数来处理(这里只是打印)不同的异常
#include <exception>
#include <system_error>
#include <future>
#include <iostream>
template <typename T>
void processCodeException (const T& e)
{
using namespace std;
auto c = e.code();
cerr << "- category: " << c.category().name() << endl;
cerr << "- value: " << c.value() << endl;
cerr << "- msg: " << c.message() << endl;
cerr << "- def category: "
<< c.default_error_condition().category().name() << endl;
cerr << "- def value: "
<< c.default_error_condition().value() << endl;
cerr << "- def msg: "
<< c.default_error_condition().message() << endl;
}
void processException()
{
using namespace std;
try {
throw; // rethrow exception to deal with it here
}
catch (const ios_base::failure& e) {
cerr << "I/O EXCEPTION: " << e.what() << endl;
processCodeException(e);
}
catch (const system_error& e) {
cerr << "SYSTEM EXCEPTION: " << e.what() << endl;
processCodeException(e);
}
catch (const future_error& e) {
cerr << "FUTURE EXCEPTION: " << e.what() << endl;
processCodeException(e);
}
catch (const bad_alloc& e) {
cerr << "BAD ALLOC EXCEPTION: " << e.what() << endl;
}
catch (const exception& e) {
cerr << "EXCEPTION: " << e.what() << endl;
}
catch (...) {
cerr << "EXCEPTION (unknown)" << endl;
}
}
//那么我们可以如下使用方式来处理异常
try{
}
catch(...)
{
processException();
}