9秒学院学C++11新特性

本文深入解析C++11的重要更新,包括右值引用、类型推导、Lambda函数等核心语言特性和线程支持、多元组等标准库新增功能,助力开发者高效掌握C++11关键知识点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

9秒学院C++11新特性学习笔记 

分类: C/C++ 

最近学习了C++11的新特性,将学习内容整理下来以巩固记忆,C++11的新特性,可以分为两部分,第一部分是C++11核心语言的特性,第二部分是STL标准库的新特性。学习C++11主要参考了wiki上的一篇文章,在介绍右值引用的时候还参考了MSDN上一篇文章,由于这两篇文章写的时间比较早,和实际有些出入,我的开发环境是win8,vs2012,很多C++11特性还没支持,所以只整理了vs2012已经支持了的特性。

第一部分:核心语言的特性


一. 右值引用,move语义,完美转发

1. 左值(lvalue)和右值(rvalue)的概念

c++11引入一种新式引用,名曰右值引用,语法:Type&& , const Type&&,区别于之前的&标示的左值引用。为理解右值引用,先要理解左值和右值的概念。

左值(++x),在表达式中,表达式结束时候不会消失,如:obj , *ptr , ptr[index] , ++x

右值(X++),在表达式中,是临时的,表达式结束就会“蒸发”,如:1729 , x + y , std::string("meow") , x++ 

区分左值和右值,还有另一种方法:能否取得其地址。

如果能取得其地址,是左值,如:&obj , &*ptr , &ptr[index] , &++x是合法的,是左值;

如果不能取得其地址,是右值,如:&1729 , &(x + y) , &std::string("meow") , &x++ 都是不合法的,是右值。

不管是左值还是右值,它要么是modifiable的,要么是const的,如下:

string one("cute");

const string two("fluffy");

string three() { return "kittens"; }

const string four() { return "are an essential part of a healthy diet"; }


one; // modifiable lvalue

two; // const lvalue

three(); // modifiable rvalue

four(); // const rvalue

2. 左值引用和右值引用的绑定特性

左值引用和右值引用各包含modifiable value和const value,故可以分为4种引用形式:

• modifiable lvalue reference

• const lvalue reference

• modifiable rvalue reference

• const rvalue reference

下面这个示例是测试4种引用的绑定特性,每种引用都试图绑定这4种引用的值。

[cpp] view plaincopyprint?

1. #include <iostream> 

2. using namespace std; 

3.

4. // 测试左值引用和右值引用的绑定特性 

5. /** 

6. * 左值引用和右值引用各包含modifiable value和const value,故可以分为4种引用形式: 

7. * 1. modifiable lvalue reference 

8. * 2. const lvalue reference 

9. * 3. modifiable rvalue reference 

10. * 4. const rvalue reference 

11. * 下面这个示例是测试4种引用的绑定特性,每种引用都试图绑定这4种引用的值。 

12. */ 

13.

14. string modifiable_rvalue() { 

15. return "cute"; 

16. } 

17.

18. const string const_rvalue() { 

19. return "fluffy"; 

20. } 

21.

22. int main() { 

23. string modifiable_lvalue("kittens"); 

24. const string const_lvalue("hungry hungry zombies"); 

25.

26. // A: testing modifiable lvalue reference 

27. string& a = modifiable_lvalue; 

28. string& b = const_lvalue; // cannot convert from 'const std::string' to 'std::string &' 

29. string& c = modifiable_rvalue(); 

30. string& d = const_rvalue(); // cannot convert from 'const std::string' to 'std::string &' 

31.

32. // B: testing const lvalue reference 

33. const string& e = modifiable_lvalue; 

34. const string& f = const_lvalue; 

35. const string& g = modifiable_rvalue(); 

36. const string& h = const_rvalue(); 

37.

38. // C: testing modifiable rvalue reference 

39. string&& i = modifiable_lvalue; // cannot convert from 'std::string' to 'std::string &&' 

40. string&& j = const_lvalue; // cannot convert from 'const std::string' to 'std::string &&' 

41. string&& k = modifiable_rvalue(); 

42. string&& l = const_rvalue(); // cannot convert from 'const std::string' to 'std::string &&' 

43.

44. // D: testing const rvalue reference 

45. const string&& m = modifiable_lvalue; // cannot convert from 'std::string' to 'const std::string &&' 

46. const string&& n = const_lvalue; // cannot convert from 'const std::string' to 'const std::string &&' 

47. const string&& o = modifiable_rvalue(); 

48. const string&& p = const_rvalue(); 

49.

50. return 0; 

51. } 

通过上面例子得出的结论:

1) 左值引用和右值引用: modifiable references不能绑定const修饰的值.

2.)右值引用不能绑定左值引用,无论是否const修饰的值.

利用重载函数检查自动绑定:

[cpp] view plaincopyprint?

1. #include <iostream> 

2. #include <string> 

3. using namespace std; 

4.

5. // 利用重载函数检查自动绑定 

6.

7. void meow(string& s) { 

8. cout << "meow(string&): " << s << endl; 

9. } 

10.

11. void meow(const string& s) { 

12. cout << "meow(const string&): " << s << endl; 

13. } 

14.

15. void meow(string&& s) { 

16. cout << "meow(string&&): " << s << endl; 

17. } 

18.

19. void meow(const string&& s) { 

20. cout << "meow(const string&&): " << s << endl; 

21. } 

22.

23. string rvalue_func() { 

24. return "rvalue_func()"; 

25. } 

26.

27. const string const_rvalue_func() { 

28. return "const_rvalue_func()"; 

29. } 

30.

31. int main() { 

32. string lvalue("lvalue"); 

33. const string const_lvalue("const_lvalue"); 

34.

35. meow(lvalue); 

36. meow(const_lvalue); 

37. meow(rvalue_func()); 

38. meow(const_rvalue_func()); 

39.

40. return 0; 

41. } 

运行结果:

meow(string&): lvalue

meow(const string&): const_lvalue

meow(string&&): rvalue_func()

meow(const string&&): const_rvalue_func()

请按任意键继续. . .

有个值得注意的地方:当有 const Type& 和 Type&& 重载时,modifiable rvalues bind to Type&&,其他的都bind to const Type&.


3. Move语义

std::move是获得右值的方式,通过move可以将左值转为右值。

[cpp] view plaincopyprint?

1. #include <iostream> 

2. #include <utility> 

3. #include <string> 

4. #include <vector> 

5. using namespace std; 

6.

7. int main() 

8. { 

9. std::string str = "Hello"; 

10. std::vector<std::string> v; 

11.

12. // uses the push_back(const T&) overload, which means 

13. // we'll incur the cost of copying str 

14. v.push_back(str); 

15. std::cout << "After copy, str is \"" << str << "\"\n"; 

16.

17. // uses the rvalue reference push_back(T&&) overload, 

18. // which means no strings will copied; instead, the contents 

19. // of str will be moved into the vector. This is less 

20. // expensive, but also means str might now be empty. 

21. v.push_back(std::move(str)); 

22. std::cout << "After move, str is \"" << str << "\"\n"; 

23.

24. std::cout << "The contents of the vector are \"" << v[0] << "\", \"" << v[1] << "\"\n"; 

25. } 


运行结果:

After copy, str is "Hello"

After move, str is ""

The contents of the vector are "Hello", "Hello"

在 C++11,一个std::vector的 "move 构造函数" 对某个vector的右值引用可以单纯地从右值复制其内部 C-style 数组的指针到新的 vector,然后留下空的右值。这个操作不需要数组的复制,而且空的暂时对象的解构也不会摧毁存储器。传回vector暂时对象的函数只需要传回std::vector<T>&&。如果vector没有 move 构造函数,那么复制构造函数将被调用,以const std::vector<T> &的正常形式。 如果它确实有 move 构造函数,那么就会调用 move 构造函数,这能够免除大幅的存储器配置。 

二. 类型推导

有被明确初始化的变量可以使用 auto 关键字

使用auto可以减少冗余代码,举例而言,程序员不用写像下面这样:

[cpp] view plaincopyprint?

1. for (vector<int>::const_iterator itr = myvec.cbegin(); itr != myvec.cend(); ++itr) 

而可以用更简短的

[cpp] view plaincopyprint?

1. for (auto itr = myvec.cbegin(); itr != myvec.cend(); ++itr) 

这里的cbegin()和cend也是c++11新加入的,因为begin(),和end()函数在容器中都有两个,一个返回iterator,

另一个返回const_iterator,因为有auto关键字,编译器将右值推导成哪个不明确,所以对容器内容只读时推荐使用cbegin()和cend()

三. 以范围为基础的 for 循环

for 语句将允许简单的范围迭代:

[cpp] view plaincopyprint?

1. int my_array[5] = {1, 2, 3, 4, 5}; 

2. for (int &x : my_array) 

3. { 

4. x *= 2; 

5. } 


四. Lambda函数与表示式

在调用C++标准程序库算法函数诸如算法函数诸如sort和find_if时候,第3个参数往往需要输入一个函数对象,既麻烦又冗赘,

还好C++11有了Lambda的支持,举例而言,程序员不用写像下面这样:

[cpp] view plaincopyprint?

1. // 查找字符串长度是5的Data 

2. struct Cmpare 

3. { 

4. Cmpare(int n) : len_(n) 

5. {} 

6.

7. bool operator()(const Data& d) 

8. { 

9. return (d.data_.length() == len_); 

10. } 

11.

12. private: 

13. int len_; 

14. }; 

15. vector<Data>::iterator it = std::find_if(my_vec.begin(), my_vec.end(), Cmpare(5)); 

而可以用Lambda函数代替:

[cpp] view plaincopyprint?

1. int find_len = 5; 

2. it = std::find_if(my_vec.begin(), my_vec.end(), [find_len](const Data& d) { 

3. return (d.data_.length() == find_len); 

4. }); 

Lambda函数体内需要什么变量,就在方括号中指明,方括号内容的含义:

[] // 沒有定义任何参数。使用未定义参数会导致错误。

[x, &y] // x 以传值方式传入,y 以传引用方式传入。

[&] // 任何被使用到的外部参数皆以引用方式使用。

[=] // 任何被使用到的外部参数皆以传值方式使用。

[&, x] // x 显式地以传值方式加以使用。其余参数以传入方式使用。

[=, &z] // z 显式地以引用方式加以使用。其余参数以传值方式使用。

在成员函数中指涉对象的 this 指针,必须要显式的传入 lambda 函数, 否则成员函数中的 lambda 函数无法使用任何该对象的变量或函数。

[this]() { this->SomePrivateMemberFunction(); };

五. 显示虚函数重载 override final关键字

为防止子类重载的函数与基类函数不一致的情况发生,在编译期期捕获倒错误,语法如下:

[cpp] view plaincopyprint?

1. struct Base { 

2. virtual void some_func(float); 

3. }; 

4.

5. struct Derived : Base { 

6. virtual void some_func(int) override; // Error: Derive::some_func 并没有 override Base::some_func 

7. virtual void some_func(float) override; // OK:显示重载 

8. }; 

C++11也提供关键字final,用来避免类被继承,或是基类的函数被改写:

[cpp] view plaincopyprint?

1. struct Base1 final { }; 

2.

3. struct Derived1 : Base1 { }; // Error: class Base1 以标明为 final 

4.

5. struct Base2 { 

6. virtual void f() final; 

7. }; 

8.

9. struct Derived2 : Base2 { 

10. void f(); // Error: Base2::f 以标明为 final 

11. }; 

六. 空指针

C++11 引入了新的关键字来代表空指针常数:nullptr

[cpp] view plaincopyprint?

1. char* pc = nullptr; // OK 

2. int * pi = nullptr; // OK 

3. int i = nullptr; // error 

4.

5. foo(nullptr); // 呼叫 foo(char *) 


这部分先介绍到这里,C++11给程序员带来了不少实惠,在这些新特性里我最喜爱的依次是:右值引用,Lambda表达式,auto关键字,虽然现在项目组还在用VS2005开发程序,但我已经迫不及待地自己使用C++11了。

第二部分:标准库的变更

这部分我想简单提一下,具体写出来不是一两遍博客可以完成的,再说也没必要,可以参考cppReference上详细的说明。

1. 线程支持

标准库提供了std::thread,还提供了线程同步的锁(如std::mutex,std::recursive_mutex),可以 RAII 锁 (std::lock_guard 和 std::unique_lock)。

2. 多元组

还记得boost库中的tuple了吗?现在已经引入到了C++11

[cpp] view plaincopyprint?

1. // 多元组类别 

2. std::tuple<int, std::string, float> Person(12, "amy", 30.1f); 

3. int id = std::get<0>(Person); 

4. std::string name = std::get<1>(Person); // "amy" 

3. 正则表达式

4. 智能指针

std::shared_ptr不用说了,boost库里有的,unique_ptr我想和boost::scoped_ptr一样使用就行了吧,头文件<memory>

5. 包装引用

std::ref,将值转成引用


转载于:https://my.oschina.net/u/2410408/blog/481361

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值