在实验室看大牛师兄的C++代码,边看边学,并作一些小笔记。
1. C++11 中的初始化列表:统一初始化的语法和语义
参考 这里。
对于所有的初始化,均可使用“{}-初始化变量列表”:
X x1 = X{1,2};
X x2 = {1,2}; // 此处的'='可有可无
X x3{1,2};
X* p = new X{1,2};
struct D : X {
D(int x, int y) :X{x,y} { /* … */ };
};
struct S {
int a[3];
// 对于旧有问题的解决方案
S(int x, int y, int z) :a{x,y,z} { /* … */ };
};
X x{a};
X* p = new X{a};
z = X{a}; // 使用了类型转换
f({a}); // a作为函数的X型实参
return {a}; // a作为函数的X型返回值
2. Explicitly defaulted and deleted special member functions (显示默认或禁用某个成员函数)
参考 这里。
C++11 allows the explicit defaulting and deleting of these special member functions.[12] For example, the following type explicitly declares that it is using the default constructor:
struct SomeType {
SomeType() = default; //The default constructor is explicitly stated.
SomeType(OtherType value);
};
Alternatively, certain features can be explicitly disabled. For example, the following type is non-copyable:
struct NonCopyable {
NonCopyable() = default;
NonCopyable(const NonCopyable&) = delete;
NonCopyable & operator=(const NonCopyable&) = delete;
};
The = delete specifier can be used to prohibit calling any function, which can be used to disallow calling a member function with particular parameters. For example:
struct NoInt {
void f(double i);
void f(int) = delete;
};
An attempt to call f() with an int will be rejected by the compiler, instead of performing a silent conversion to double. This can be generalized to disallow calling the function with any type other than double as follows:
struct OnlyDouble {
void f(double d);
template<class T> void f(T) = delete;
};
3. 可变参数
http://www.cplusplus.com/reference/cstdarg/va_list/
4. GNU C __attribute__ 机制
参考:
http://www.unixwiz.net/techtips/gnu-c-attributes.html
http://blog.csdn.net/ruixj/article/details/4274721
One of the best (but little known) features of GNU C is the __attribute__ mechanism, which allows a developer to attach characteristics to function declarations to allow the compiler to perform more error checking.
5. final 和 overide 关键字:避免更多的程序错误
参考:
http://www.devbean.net/2012/05/cpp11-override-final/
6. constexpr specifier (since C++11)
http://en.cppreference.com/w/cpp/language/constexpr
7. Move Constructor and the Move Assignment Operator
初始化的时候可以使用move提升效率,如:
base_argument(std::string n, bool a): _name(std::move(n)), _app(a) {}
8. initializer_list
http://www.cplusplus.com/reference/initializer_list/initializer_list/?kw=initializer_list
初始化数组成员时效率更高. 如:
class configure_manager {
private:
typedef std::reference_wrapper<base_argument> ref_type;
std::vector<ref_type> _args;
hash_map<std::string, ref_type> _dict;
public:
configure_manager(std::initializer_list<ref_type> ls): _args(ls) {
for (ref_type r : ls) {
_dict.insert({r.get().name(), r});
}
}
}
9. unordered_map, unordered_set
两者都是用hash表实现的,效率非常高。
10. forward 函数模板
http://www.cplusplus.com/reference/utility/forward/?kw=forward
生成右值引用。
11. decay模板
获取参数类型.
12. bind模板
可以将多参数的函数转换为指定个数参数的函数
13. atomic模板
多线程相关. 原子操作.