看的是一个来自微软的视频教程,记录笔记如下:
Language and Library updates
C++0x and TR1
TR1 is the Technical Report 1, released in 2005; C++0x is the upcoming C++ standard; Some of each were added in VC9SP1, and more are now in VC10
Lambdas
Lambda expression or lambda function: an expression that specifies an anonymous function object(匿名的函数对象). Imagine handing an operation or function(code) to some other operation or function. lambda的表面意义是:希腊语的第11个字母(Λλ)
Lambda can be used for generic work, a functional style, concurrency, readability(eliminate tiny functions).
1: void print_square(int n) {
2: cout << n*n << endl;
3: }
4:
5: int main() {
6: vector<int> v;
7: v.push_back(0);
8: v.push_back(1);
9: for_each(v.begin(), v.end(), print_square);
10: }
很显然,上面的print_square(int)是一个tiny function,还好print_square(int)就在main()上面,省去了查找的方便,不过如果在其他位置呢?而且,这样的一个function是否有必要。下面就使用lambda来修改它:将print_square(int)的代码转换为lambda,也就是一个匿名的函数对象。如下(看看可读性如何)
1: int main() {
2: vector<int> v;
3: v.push_back(2);
4: v.push_back(3);
5: for_each(v.begin(), v.end(),
6: [](int n) { cout << n*n << endl;});
7: //[] -- Hi, I'm a lambda
8: //(int n) -- parameters for the lambda to operate on
9: //{...} -- main body(do something with the integer n)
10:
11: v.clear();
12: }
auto
对于我们“无法说出”的类型,但是compiler知道,用auto告诉它让它自己去deduction。同时,有些类型比较“难写”,也让compiler帮助我们做吧。auto也可以和pointer、reference结合起来使用。
1: //Automatic type deduction
2: auto x = new HugeObject(42);
3: //No more gnarly iterator declaration
4: for (auto it = v.begin(); it != v.end(); ++it)
5: //Poaered by template argument deduction rules
6: const auto* p = new foo;
7: const auto& r = bar;
C++0x Standard Library in VC2010
1: Revalue reference:
2: vector reallocation, etc. exploits move semantics
3: Perfect forwarding: make_shared
(), etc
4: std::move
5: unique_ptr
6: New member functions: cbegin(), cend(), etc
7: New algorithms: copy_if(), is_sorted(), etc
8: Code conversions:
9: Exception progagation: exception_ptr
10: Diagnostics:
Smart pointers
shared_ptr arrved in VC9SP1 and in VC10: make_shared. unique_ptr looks like a shared_ptr without the sharing.
1: //VC9 SP1
2: shared_ptr sp( new T(args));
3: shared_ptr sp( new T(args), del, alloc);
4:
5: //VC10
6: auto sp = make_shared
(args);
7: auto sp = allocate_shared
(alloc, args);
8:
9: //unique_ptr
10: //Supersedes auto ptr, whici is noe deprecated
11: //Lightweight and performant
12: // No reference counting overhead
13: //Noncopyable but movable
14: //Works just fine in containers
const iterators: cbegin and cend
1: vector<int> v;
2: for (auto it = v.begin(); it != v.end(); ++it) {
3: //it is vectotr ::iterator
4: }
5:
6: for (auto it = v.cbegin(); it != v.cend(); ++it) {
7: //it is vector ::const_iterator
8: }