C++代码阅读笔记

rpc

for(;;)循环

1
2
3
while(true);
//等价于
for(;;)

某些编译器对while(1)警告,效率略有不同

emplace_back()

在容器尾部添加一个元素,这个元素原地构造,不需要触发拷贝构造和转移构造。而且调用形式更加简洁,直接根据参数初始化临时对象的成员。
比push_back()效率高。

std::unique_lock与std::lock_guard区别

std::unique_lock相对std::lock_guard更灵活的地方在于在等待中的线程如果在等待期间需要解锁mutex,并在之后重新将其锁定。而std::lock_guard却不具备这样的功能。

带箭头的函数声明

In C++11, there are two syntaxes for function declaration:

1
return-type identifier ( argument-declarations... )

1
auto identifier ( argument-declarations... ) -> return_type

下面一种方便使用decltype

explicit

按照默认规定,只有一个参数的构造函数也定义了一个隐式转换,将该构造函数对应数据类型的数据转换为该类对象,如下面所示:
class String {
String ( const char* p ); // 用C风格的字符串p作为初始化值
//…
}
String s1 = “hello”; //OK 隐式转换,等价于String s1 = String(“hello”);

但是有的时候可能会不需要这种隐式转换,如下:
class String {
String ( int n ); //本意是预先分配n个字节给字符串
String ( const char* p ); // 用C风格的字符串p作为初始化值
//…
}