C++11 新特性

c++11新特性


举着火把寻找电灯

enter description here


今天我就权当抛砖引玉,如有不解大家一起探讨。有部分内容是引用自互联网上的内容,如有问题请联系我。


T&& 右值引用 std::move

右值引用出现之前我们只能用const引用来关联临时对象(右值)所以我们不能修临时对象的内容,右值引用的出现就让我们可以取得临时对象的控制权,终于可以修改临时对象了!


   
   
  1. int main()
  2. {
  3. int i = 42;
  4. int &r = i; // ok: r refers to i
  5. int &&rr = i; // error: cannot bind an rvalue reference to an lvalue
  6. int &r2 = i * 42; // error: i * 42 is an rvalue
  7. const int &r3 = i * 42; // ok: we can bind a reference to const to an rvalue
  8. int &&rr2 = i * 42;
  9. int &&rr3 = rr2; // error: the expression rr2 is an lvalue!
  10. return 0;
  11. }

即凡是可以 vartype varname; 这样定义出来的变量(variable)其自身都是左值。

std::move相关。 右值引用因为绑定对象即将被销毁,意味着没有人会继续访问他们,所以就可以把他们(的资源)steal(偷)过来。 虽然不能将右值引用绑在左值上,但通过利用utility头文件新增的函数模板move,它返回传入对象的右值引用,可以达到 steal的效果。

int &&rr3 = std::move(rr2); // ok

再提醒:一旦使用了move,编译器就默认传入对象已经不打算使用了,是可以被销毁的,move之后该对象的值已经不确定,不要再访问。还有由于对象偷取与复制的差别巨大,不注意会产生非常难定位的bug,所以所有使用move的地方一定要使用全称std::move,给大家以提醒。(其实c++11在algorithm头文件也新增了一个move,参数与意义都与此截然不同)。


   
   
  1. #include <iostream>
  2. using namespace std;
  3. class HugeMem{
  4. public:
  5. HugeMem( int size): sz(size > 0 ? size : 1) {
  6. c = new int[sz];
  7. }
  8. ~HugeMem() { cout<< "HugeMem 析构\n";delete [] c; }
  9. HugeMem(HugeMem && hm): sz(hm.sz), c(hm.c) {
  10. cout<< "HugeMem move 构造\n";
  11. hm.c = nullptr;
  12. }
  13. int * c;
  14. int sz;
  15. };
  16. class Moveable{
  17. public:
  18. Moveable():i( new int( 3)), h( 1024) {}
  19. ~Moveable() { cout<< "Moveable 析构\n";delete i; }
  20. Moveable(Moveable && m):
  21. i(m.i), h(move(m.h)) { // 强制转为右值,以调用移动构造函数
  22. m.i = nullptr;
  23. }
  24. int* i;
  25. HugeMem h;
  26. };
  27. Moveable GetTemp() {
  28. //Moveable tmp = Moveable();
  29. Moveable tmp;
  30. cout << hex << "Huge Mem from " << __func__
  31. << " @" << tmp.h.c << endl; // Huge Mem from GetTemp @0x603030
  32. return tmp;
  33. }
  34. int main() {
  35. Moveable a(GetTemp());
  36. cout << hex << "Huge Mem from " << __func__
  37. << " @" << a.h.c << endl; // Huge Mem from main @0x603030
  38. }

早在C++11之前编译器就把优化几乎做到了极致——局部变量返回到函数外部并赋值给外部变量这个过程基本上不存在任何多余的临时变量构造和析构,这比move机制更加高效。显式指定move以后,return std::move(localvar)这里会强行从localvar移动构造一个临时变量temp,然后return temp(temp这里会有RVO优化)。

auto for循环

需要注意的是,auto不能用来声明函数的返回值。但如果函数有一个尾随的返回类型时,auto是可以出现在函数声明中返回值位置。这种情况下,auto并不是告诉编译器去推断返回类型,而是指引编译器去函数的末端寻找返回值类型。在下面这个例子中,函数的返回值类型就是operator+操作符作用在T1、T2类型变量上的返回值类型。


   
   
  1. template < typename T1, typename T2>
  2. auto compose(T1 t1, T2 t2) -> **decltype**(t1 + t2)
  3. {
  4. return t1+t2;
  5. }
  6. auto v = compose( 2, 3.14); // v's type is double

auto与for配合使用


   
   
  1. std:: map< std:: string, std:: vector< int>> map;
  2. std:: vector< int> v;
  3. v.push_back( 1);
  4. v.push_back( 2);
  5. v.push_back( 3);
  6. map[ "one"] = v;
  7. for( const auto& kvp : map)
  8. {
  9. std:: cout << kvp.first << std:: endl;
  10. for( auto v : kvp.second)
  11. {
  12. std:: cout << v << std:: endl;
  13. }
  14. }
  15. int arr[] = { 1, 2, 3, 4, 5};
  16. for( int& e : arr)
  17. {
  18. e = e*e;
  19. }

std::lambda

“Lambda 表达式”(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数。

C++11 的 lambda 表达式规范如下:

[ capture ] ( params ) mutable exception attribute -> ret { body } (1) [ capture ] ( params ) -> ret { body } (2) [ capture ] ( params ) { body } (3) [ capture ] { body } (4) 其中

(1) 是完整的 lambda 表达式形式, (2) const 类型的 lambda 表达式,该类型的表达式不能改捕获(“capture”)列表中的值。 (3)省略了返回值类型的 lambda 表达式,但是该 lambda 表达式的返回类型可以按照下列规则推演出来: 如果 lambda 代码块中包含了 return 语句,则该 lambda 表达式的返回类型由 return 语句的返回类型确定。 如果没有 return 语句,则类似 void f(…) 函数。 省略了参数列表,类似于无参函数 f()。

[] // 不引用外部变量 [x, &y] // x引用方式 ,y 传值 [&] // 任何使用的外部变量都是引用方式。 [=] // 任何被使用到的外部都是传值方式。 [&, x] // 除x传值以外其他的都以引用方式。 [=, &z] // 除z引用以外其他的都是以传值方式使用。


   
   
  1. int main()
  2. {
  3. std:: vector< int> c { 1, 2, 3, 4, 5, 6, 7 };
  4. int x = 5;
  5. c.erase( std::remove_if(c.begin(), c.end(), [x]( int n) { return n < x; } ), c.end());
  6. std:: cout << "c: ";
  7. for ( auto i: c) {
  8. std:: cout << i << ' ';
  9. }
  10. std:: cout << '\n';
  11. // 可以用auto 接收一个lambda 表达式。
  12. auto func1 = []( int i) { return i+ 4; };
  13. std:: cout << "func1: " << func1( 6) << '\n';
  14. // std::function 也可以接收lambda 表达式。
  15. std::function< int( int)> func2 = []( int i) { return i+ 4; };
  16. std:: cout << "func2: " << func2( 6) << '\n';
  17. std::function< int()> func3 = [x]{ return x;};
  18. std:: cout << "func3: " << func3() << '\n';
  19. std:: vector< int> someList = { 1, 2, 3}; //这里是c++11
  20. int total = 0;
  21. double sum = 0.0f;
  22. std::for_each(someList.begin(), someList.end(), [&total]( int x) { total += x; });
  23. std:: cout << total << '\n';
  24. std::for_each(someList.begin(), someList.end(), [&]( int x){ total += x; sum += x;});
  25. std:: cout << total << '\n';
  26. std:: cout << sum << '\n';
  27. //再写一种简单的lambda
  28. [](){ std:: cout<< "就地展开的lambda\n";}();
  29. }

bind

std::bind是STL实现函数组合概念的重要手段,std::bind绑定普通函数(函数指针)、lambda表达式、成员函数、成员变量、模板函数等


   
   
  1. #include <iostream>
  2. #include <functional>
  3. void f( int n1, int n2, int n3, const int& n4, int n5)
  4. {
  5. std::cout << n1 << ' ' << n2 << ' ' << n3 << ' ' << n4 << ' ' << n5 << '\n';
  6. }
  7. int g( int n1)
  8. {
  9. return n1;
  10. }
  11. struct Foo {
  12. void print_sum( int n1, int n2)
  13. {
  14. std::cout << n1+n2 << '\n';
  15. }
  16. static void static_func(std::function< int( int)> f, int n)
  17. {
  18. std::cout<< "call static_func\n";
  19. std::cout<< "f(n):\t"<<f(n)<< "\n";
  20. }
  21. int data = 10; //c++11 支持声明是就初始化值
  22. };
  23. int main()
  24. {
  25. using namespace std::placeholders;
  26. // std::cref(n) 表示要把n以引用的方式传入
  27. int n = 7;
  28. auto f1 = std::bind(f, _2, _1, 42, std::cref(n), n);
  29. n = 10;
  30. f1( 1, 2, 1001); // 1 is bound by _1, 2 is bound by _2, 1001 is unused
  31. // 绑定一个子表达式,用_3替换了 其他位置的变量
  32. // std::bind(g, _3) 在这里已经表示int
  33. auto f2 = std::bind(f, _4, std::bind(g, _4), _4, 4, 5);
  34. f2( 10, 11, 12 , 13);
  35. // 绑定成员函数
  36. Foo foo;
  37. auto f3 = std::bind(&Foo::print_sum, foo, 95, _1);
  38. f3( 5);
  39. // 绑定成员变量
  40. auto f4 = std::bind(&Foo::data, _1);
  41. std::cout << f4(foo) << '\n';
  42. // 绑定静态成员函数
  43. auto f5 = std::bind(&Foo::static_func,g,_1);
  44. f5( 3);
  45. }

std::function

通过std::function对C++中各种可调用实体(普通函数、Lambda表达式、函数指针、以及其它函数对象等)的封装,形成一个新的可调用的std::function对象;让我们不再纠结那么多的可调用实体。

转换后的std::function对象的参数能转换为可调用实体的参数; 可调用实体的返回值能转换为std::function对象的返回值。 std::function对象最大的用处就是在实现函数回调(实际工作中就是用到了这一点),使用者需要注意,它不能被用来检查相等或者不相等,但是可以与NULL或者nullptr进行比较。


   
   
  1. #include <functional>
  2. #include <iostream>
  3. using namespace std;
  4. std::function< int( int)> Functional;
  5. // 普通函数
  6. int TestFunc(int a)
  7. {
  8. return a;
  9. }
  10. // Lambda表达式
  11. auto lambda = []( int a)-> int{ return a; };
  12. // 仿函数(functor)
  13. class Functor
  14. {
  15. public:
  16. int operator()(int a)
  17. {
  18. return a;
  19. }
  20. };
  21. // 1.类成员函数
  22. // 2.类静态函数
  23. class TestClass
  24. {
  25. public:
  26. int ClassMember(int a) { return a; }
  27. static int StaticMember(int a) { return a; }
  28. };
  29. int main()
  30. {
  31. // 普通函数
  32. Functional = TestFunc;
  33. int result = Functional( 10);
  34. cout << "普通函数:"<< result << endl;
  35. // Lambda表达式
  36. Functional = lambda;
  37. result = Functional( 20);
  38. cout << "Lambda表达式:"<< result << endl;
  39. // 仿函数
  40. Functor testFunctor;
  41. Functional = testFunctor;
  42. result = Functional( 30);
  43. cout << "仿函数:"<< result << endl;
  44. // 类成员函数
  45. TestClass testObj;
  46. Functional = std::bind(&TestClass::ClassMember, testObj, std::placeholders::_1);
  47. result = Functional( 40);
  48. cout << "类成员函数:"<< result << endl;
  49. // 类静态函数
  50. Functional = TestClass::StaticMember;
  51. result = Functional( 50);
  52. cout << "类静态函数:"<< result << endl;
  53. return 0;
  54. }

initializer_list

过往,我们这样给vector赋值:


   
   
  1. std ::vector v;
  2. v .push_back(1);
  3. v .push_back(2);
  4. v .push_back(3);
  5. v .push_back(4);

需要感谢的是,C++11让你更方便。

std::vector v = { 1, 2, 3, 4 };

   
   

这就是所谓的initializer list。更进一步,有一个关键字叫initializer list


   
   
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <string>
  5. #include <typeinfo>
  6. class MyNumber
  7. {
  8. public:
  9. MyNumber( const std:: initializer_list< int> &v) {
  10. for ( auto itm : v) {
  11. mVec.push_back(itm);
  12. }
  13. }
  14. void print() {
  15. for ( auto itm : mVec) {
  16. std:: cout << itm << " ";
  17. }
  18. }
  19. private:
  20. std:: vector< int> mVec;
  21. };
  22. class Test {
  23. public:
  24. void show()
  25. {
  26. for( auto kv : nameToBirthday)
  27. {
  28. std:: cout<< "key:\t"<<kv.first<< "\tvalue:\t"<<kv.second<< "\n";
  29. }
  30. }
  31. private:
  32. static std:: map< std:: string, std:: string> nameToBirthday;
  33. };
  34. std:: map< std:: string, std:: string> Test::nameToBirthday = {
  35. { "lisi", "18841011"},
  36. { "zhangsan", "18850123"},
  37. { "wangwu", "18870908"},
  38. { "zhaoliu", "18810316"}
  39. };
  40. class CompareClass
  41. {
  42. public:
  43. CompareClass ( int, int)
  44. { std:: cout<< "call old const\n";}
  45. CompareClass ( std:: initializer_list < int> )
  46. { std:: cout<< "call initializer_list const\n";}
  47. };
  48. int main()
  49. {
  50. MyNumber m = { 1, 2, 3, 4 };
  51. m.print(); // 1 2 3 4
  52. Test t;
  53. t.show();
  54. std:: map< int, int> ii_map = {{ 1, 1},{ 2, 2}};
  55. CompareClass foo { 10, 20}; // calls initializer_list ctor
  56. CompareClass bar (10,20); // calls first constructor
  57. for( auto kv : ii_map)
  58. {
  59. std:: cout<< "key:\t"<< typeid(kv.first).name()<< "\n";
  60. }
  61. return 0;
  62. }

thread

http://blog.csdn.net/tujiaw/article/details/8245130


   
   
  1. #include <thread>
  2. void my_thread()
  3. {
  4. puts( "hello, world");
  5. }
  6. int main(int argc, char *argv[])
  7. {
  8. std:: thread t(my_thread);
  9. t.join();
  10. system( "pause");
  11. return 0;
  12. }

编译命令 g++ -std=c++11 thread0.cpp -o thread0 -lpthread

实例化一个线程对象t,参数mythread是一个函数,在线程创建完成后将被执行,t.join()等待子线程mythread执行完之后,主线程才可以继续执行下去,此时主线程会释放掉执行完后的子线程资源。


   
   
  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <thread>
  4. #include <string>
  5. #include <unistd.h>
  6. void my_thread(int num, const std::string& str)
  7. {
  8. std:: cout << "num:" << num << ",name:" << str << std:: endl;
  9. }
  10. int main(int argc, char *argv[])
  11. {
  12. int num = 1234;
  13. std:: string str = "tujiaw";
  14. std:: thread t(my_thread, num, str);
  15. t.detach(); //子线程从主线程中分离出去
  16. // sleep(1);
  17. return 0;
  18. }

互斥量 多个线程同时访问共享资源的时候需要需要用到互斥量,当一个线程锁住了互斥量后,其他线程必须等待这个互斥量解锁后才能访问它。thread提供了四种不同的互斥量: 独占式互斥量non-recursive (std::mutex) 递归式互斥量recursive (std::recursivemutex) 允许超时的独占式互斥量non-recursive that allows timeouts on the lock functions(std::timedmutex) 允许超时的递归式互斥量recursive mutex that allows timeouts on the lock functions (std::recursivetimedmutex)


   
   
  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <thread>
  4. #include <string>
  5. #include <mutex>
  6. int g_num = 0;
  7. std::mutex g_mutex;
  8. void thread1()
  9. {
  10. g_mutex.lock(); //线程加锁
  11. g_num = 10;
  12. for ( int i= 0; i< 10; i++)
  13. {
  14. std:: cout << "thread1:" << g_num << "\tthread id:\t"<< std::this_thread::get_id() << std:: endl;
  15. }
  16. g_mutex.unlock();
  17. }
  18. void thread2()
  19. {
  20. std::lock_guard< std::mutex> lg(g_mutex); //自动锁
  21. g_num = 20;
  22. for ( int i= 0; i< 10; i++)
  23. {
  24. std:: cout << "thread2:" << g_num << "\tthread id:\t"<< std::this_thread::get_id() << std:: endl;
  25. }
  26. }
  27. int main(int argc, char *argv[])
  28. {
  29. std:: thread t1(thread1);
  30. std:: thread t2(thread2);
  31. if(t1.joinable()) t1.join();
  32. // t1.join();
  33. // std::thread t3 = t2; //thread 对象禁止复制。 thread& operator= (const thread&) = delete;
  34. std::thread t3 = std::move(t2);
  35. if(t3.joinable()) t3.join();
  36. return 0;
  37. }

std::thread 不仅能实现函数的绑定,成员函数,仿函数都可以。至于lambda 我就没有试过了。

简单的线程池实现


   
   
  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <functional>
  4. #include <thread>
  5. #include <string>
  6. #include <mutex>
  7. #include <condition_variable>
  8. #include <vector>
  9. #include <memory>
  10. #include <assert.h>
  11. #include <algorithm>
  12. #include <queue>
  13. class ThreadPool
  14. {
  15. public:
  16. typedef std::function<void()> Task;
  17. ThreadPool(int num)
  18. : num_(num)
  19. , maxQueueSize_( 0)
  20. , running_( false)
  21. {
  22. }
  23. ~ThreadPool()
  24. {
  25. if (running_) {
  26. stop();
  27. }
  28. }
  29. ThreadPool( const ThreadPool&) = delete;
  30. void operator=( const ThreadPool&) = delete;
  31. void setMaxQueueSize(int maxSize)
  32. {
  33. maxQueueSize_ = maxSize;
  34. }
  35. void start()
  36. {
  37. assert(threads_. empty());
  38. running_ = true;
  39. threads_.reserve(num_);
  40. for (int i = 0; i<num_; i++) {
  41. threads_.push_back(std::thread(std::bind(&ThreadPool::threadFunc, this)));
  42. }
  43. }
  44. void stop()
  45. {
  46. {
  47. std::unique_lock<std::mutex> ul(mutex_);
  48. running_ = false;
  49. notEmpty_.notify_all();
  50. }
  51. for (auto &iter : threads_) {
  52. iter.join();
  53. }
  54. }
  55. void run( const Task &t)
  56. {
  57. if (threads_. empty()) {
  58. t();
  59. }
  60. else {
  61. std::unique_lock<std::mutex> ul(mutex_);
  62. while (isFull()) {
  63. notFull_.wait(ul);
  64. }
  65. assert(!isFull());
  66. queue_.push_back(t);
  67. notEmpty_.notify_one();
  68. }
  69. }
  70. private:
  71. bool isFull() const
  72. {
  73. return maxQueueSize_ > 0 && queue_.size() >= maxQueueSize_;
  74. }
  75. void threadFunc()
  76. {
  77. while (running_)
  78. {
  79. Task task(take());
  80. if (task) {
  81. std::lock_guard<std::mutex> lg(mutex_out); //自动锁
  82. printf( "thread id:%d\n", std::this_thread::get_id());
  83. task();
  84. printf( "thread id:%d\n", std::this_thread::get_id());
  85. }
  86. }
  87. }
  88. Task take()
  89. {
  90. std::unique_lock<std::mutex> ul(mutex_);
  91. while (queue_. empty() && running_) {
  92. notEmpty_.wait(ul);
  93. }
  94. Task task;
  95. if (!queue_. empty()) {
  96. task = queue_.front();
  97. queue_.pop_front();
  98. if (maxQueueSize_ > 0) {
  99. notFull_.notify_one();
  100. }
  101. }
  102. return task;
  103. }
  104. private:
  105. int num_;
  106. std::mutex mutex_;
  107. std::mutex mutex_out;
  108. std::condition_variable notEmpty_;
  109. std::condition_variable notFull_;
  110. std::vector<std::thread> threads_;
  111. std::deque<Task> queue_;
  112. size_t maxQueueSize_;
  113. bool running_;
  114. };
  115. void fun()
  116. {
  117. printf( "[id:%d] hello, world!\n", std::this_thread::get_id());
  118. }
  119. int main()
  120. {
  121. {
  122. printf( "main thread id:%d\n", std::this_thread::get_id());
  123. ThreadPool pool( 3);
  124. pool.setMaxQueueSize( 100);
  125. pool.start();
  126. //std::this_thread::sleep_for(std::chrono::milliseconds(3000));
  127. for (int i = 0; i < 1000; i++) {
  128. pool.run(fun);
  129. }
  130. std::this_thread::sleep_for(std::chrono::milliseconds( 3000));
  131. }
  132. return 0;
  133. }

atomic

原子操作


   
   
  1. #include <thread>
  2. #include <atomic>
  3. #include <iostream>
  4. #include <time.h>
  5. #include <mutex>
  6. using namespace std;
  7. // 全局的结果数据
  8. //long total = 0;
  9. std:: atomic_long total(0);
  10. //std::mutex g_mutex;
  11. // 点击函数
  12. void click()
  13. {
  14. for( int i= 0; i< 1000000;++i)
  15. {
  16. // 对全局数据进行无锁访问
  17. // std::lock_guard<std::mutex> lg(g_mutex); //自动锁
  18. total += 1;
  19. }
  20. }
  21. int main(int argc, char* argv[])
  22. {
  23. // 计时开始
  24. clock_t start = clock();
  25. // 创建100个线程模拟点击统计
  26. std::thread threads[ 100];
  27. for( int i= 0; i< 100;++i)
  28. {
  29. threads[i] = std::thread(click);
  30. }
  31. for( auto& t : threads)
  32. {
  33. t.join();
  34. }
  35. // 计时结束
  36. clock_t finish = clock();
  37. // 输出结果
  38. cout<< "result:"<<total<< endl;
  39. cout<< "duration:"<<finish -start<< "us"<< endl;
  40. return 0;
  41. }

shared_ptr

这个sharedptr 相信大家都已经在boost中用过了。这里就不用详细介绍了,反正是在能用原始指针的地方就能替换成 sharedptr。 #include #include


   
   
  1. struct Foo {
  2. Foo() { std:: cout << "constructor Foo...\n"; }
  3. Foo(Foo&f)
  4. {
  5. std:: cout<< "copy constructor Foo...\n";
  6. }
  7. void show(int i)
  8. {
  9. std:: cout<< "show Foo "<<i<< "\n";
  10. }
  11. ~Foo() { std:: cout << "~Foo...\n"; }
  12. };
  13. struct D {
  14. void operator()(Foo* p) const {
  15. std:: cout << "Call delete for Foo object...\n";
  16. delete p;
  17. }
  18. };
  19. void needptr( Foo* fn,int i)
  20. {
  21. fn->show(i);
  22. }
  23. void needshptr(std::shared_ptr<Foo> shptr,int i)
  24. {
  25. shptr->show(i);
  26. std:: cout<< shptr.use_count()<< '\n';
  27. }
  28. int main()
  29. {
  30. // 只形成一个指针
  31. std:: shared_ptr<Foo> sh1; //
  32. needptr(sh1.get(), 1);
  33. auto shfn = std::make_shared<Foo>(); // 调用构造函数
  34. shfn->show( 2);
  35. //
  36. std:: shared_ptr<Foo> sh2( new Foo);
  37. std:: shared_ptr<Foo> sh3(sh2);
  38. std:: cout << sh2.use_count() << '\n';
  39. std:: cout << sh3.use_count() << '\n';
  40. needshptr(sh3, 3);
  41. std:: cout << sh3.use_count() << '\n';
  42. //constructor with object and deleter
  43. std:: shared_ptr<Foo> sh4( new Foo, D());
  44. }

override和final关键字

override 强制检查虚函数 final 禁止虚函数继续重写

高质量C++C 编程指南 访问密码 5de8

override 用法


   
   
  1. #include <string>
  2. #include <iostream>
  3. #include <stdint.h>
  4. #include <stdio.h>
  5. class G
  6. {
  7. public:
  8. virtual void func(double a)
  9. {
  10. std:: cout<< "G::func="<<a<< std:: endl;
  11. }
  12. };
  13. class H: public G
  14. {
  15. public:
  16. int a;
  17. int b;
  18. void test()
  19. {
  20. std:: cout<< "Normal func"<< std:: endl;
  21. }
  22. // 同名函数被隐藏了
  23. virtual void func(int a) //override //c++11 中添加这个关键字就能解决这一问题
  24. {
  25. std:: cout<< "H::func="<<a<< std:: endl;
  26. }
  27. };
  28. typedef void (*FuncD)(double a);
  29. typedef void (*FuncI)(int a);
  30. typedef void (H::*Func)();
  31. //节选自 林锐博士的 《高质量C++C 编程指南》 8.2 章节
  32. //重载的特征:
  33. //  1、处在相同的空间中,即相同的范围内。
  34. //  2、函数名相同。
  35. //  3、参数不同,即参数个数不同,或相同位置的参数类型不同。
  36. //  4、virtual 关键字对是否够成重载无任何影响。
  37. //  每个类维护一个自己的名字空间,即类域,所以派生类跟基类处于不同的空间之中,因些,虽然派生类自动继承了基类的成员变量及成员函数,但基类的函数跟派生类的函数不可能直接够成函数重载,因为它们处于两个不同的域。
  38. //
  39. //  隐藏规则:
  40. //  1、派生类的函数跟基类的函数同名,但是参数不同,此时,不论有没有virtual关键字,基类函数将被隐藏。
  41. //  2、派生类的函数跟基类的函数同名,且参数也样,但基类没有virtual关键字,此时基类函数也将被隐藏。
  42. //隐藏规则的底层原因其实是C++的名字解析过程。
  43. //  在继承机制下,派生类的类域被嵌套在基类的类域中。派生类的名字解析过程如下:
  44. //  1、首先在派生类类域中查找该名字。
  45. //  2、如果第一步中没有成功查找到该名字,即在派生类的类域中无法对该名字进行解析,则编译器在外围基类类域对查找该名字的定义。
  46. int main(int argc,char *argv[])
  47. {
  48. H *h= new H;
  49. printf( "%x\n",h);
  50. printf( "%x\n",&H::test);
  51. printf( "%x\n",&H::func);
  52. Func func=&H::test;
  53. (h->*func)();
  54. FuncD fund=(FuncD)(*( intptr_t*)*( intptr_t*)(h));
  55. FuncI funi=(FuncI)(*(( intptr_t*)*( intptr_t*)(h)+ 1));
  56. printf( "fund=%x\n",( intptr_t*)*( intptr_t*)(h));
  57. printf( "funi=%x\n",(( intptr_t*)*( intptr_t*)(h)+ 1));
  58. fund( 10.1);
  59. funi( 10);
  60. fund((G*)h, 10.1); //需要绑定一个this指针,同时也把封装性破坏了。
  61. funi(h, 10);
  62. h->func( 5);
  63. h->func( 5.5);
  64. ((g*)h)->func( 5.5);
  65. h->G::func( 5.5);
  66. return 0;
  67. }

final 的用法


   
   
  1. #include <iostream>
  2. using namespace std;
  3. class MathObject{
  4. public:
  5. virtual double Arith() = 0;
  6. // virtual void Print() final = 0 ; // 这样写会造成凡是派生自它的子类都无法创建对象
  7. virtual void Print() = 0 ;
  8. virtual void Print2()
  9. {
  10. cout<< "this is Print2()\n";
  11. };
  12. };
  13. class Printable : public MathObject{
  14. public:
  15. double Arith() = 0;
  16. void Print() final// 在C++98中我们无法阻止该接口被重写
  17. {
  18. cout << "Output is: " << Arith() << endl;
  19. }
  20. };
  21. class Add2 final: public Printable {
  22. public:
  23. Add2( double a, double b): x(a), y(b) {}
  24. double Arith() override final{ return x + y; }
  25. private:
  26. double x, y;
  27. };
  28. class Mul3 : public Printable {
  29. public:
  30. Mul3( double a, double b, double c): x(a), y(b), z(c) {}
  31. double Arith() { return x * y * z; }
  32. // void Print() 这里无法在改写这个函数
  33. // {
  34. // cout<<"Mul3 Print\n";
  35. // }
  36. private:
  37. double x, y, z;
  38. };
  39. int main()
  40. {
  41. Add2 add2(2,3);
  42. cout<< "add2.Arith()"<<add2.Arith()<< '\n';
  43. add2.Print();
  44. Mul3 mul3(1,2,3);
  45. mul3.Print();
  46. return 0;
  47. }

delete default

设置默认构造函数时使用。在类中定义了构造函数后,还想继续使用默认构造函数,则可以在函数成员列表后添加 =default 。

可以使用在不允许使用复制构造函数和赋值构造函数上,则可以在函数成员列表后添加 =delete表示不定义。


   
   
  1. #include <iostream>
  2. class NonCopyable
  3. {
  4. public:
  5. NonCopyable & operator=( const NonCopyable&) = delete;
  6. NonCopyable( const NonCopyable&) = delete;
  7. NonCopyable( int i)
  8. {};
  9. NonCopyable() = default; // 不相当于用户在写一个 NonCopyable(void){};
  10. NonCopyable( double) = delete;
  11. void* operator new(size_t) = delete;
  12. // void* operator new[](size_t) = delete;
  13. //private:
  14. int m_i;
  15. };
  16. int main()
  17. {
  18. NonCopyable nc;
  19. // NonCopyable* pnc = new NonCopyable();
  20. NonCopyable *pncs = new NonCopyable[ 10]();
  21. std:: cout<< sizeof(NonCopyable::m_i)<< std:: endl; //sizeof 可以直接计算成员变量的大小,成员在外部必须可见。
  22. return 0;
  23. }

正则

主类

这些类封装了一个正则表达式和目标内的字符序列匹配正则表达式的结果.

basic_regex (C++11) 正则表达式对象 (类模板)

算法

使用这些功能应用正则表达式封装在一个正则表达式的字符序列目标.. regexmatch 尝试匹配正则表达式的整个字符序列 (函数模板) regexsearch 尝试匹配正则表达式的字符序列的任何部分 函数模板) regex_replace 以格式化的替换文本来替换正则表达式匹配的地方(函数模板)

正则规则


   
   
  1. #include <iostream>
  2. #include <iterator>
  3. #include <string>
  4. #include <regex>
  5. #include <fstream>
  6. #include <iterator>
  7. #include <vector>
  8. using VSS = std:: vector< std::pair< std:: string, std:: string>> ;
  9. bool regex_search_all(std::string s,VSS& o , std::string reg_str)
  10. {
  11. std:: regex r(reg_str);
  12. std::smatch m;
  13. bool ret = false;
  14. while( std::regex_search(s,m,r))
  15. {
  16. o.push_back( std::move( std::make_pair(m[ 0].str(),m[ 1].str())));
  17. s = m.suffix().str();
  18. ret = true;
  19. }
  20. return ret;
  21. }
  22. int main()
  23. {
  24. std:: string s = "Some people, when confronted with a problem, think "
  25. "\"I know, I'll use regular expressions.\" "
  26. "Now they have two problems.";
  27. // 正则匹配
  28. std:: regex self_regex("REGULAR EXPRESSIONS",
  29. std::regex_constants::ECMAScript | std::regex_constants::icase);
  30. if ( std::regex_search(s, self_regex)) {
  31. std:: cout << "Text contains the phrase 'regular expressions'\n";
  32. }
  33. std:: ifstream in("360_20160114.xml", std::ios::in);
  34. std::istreambuf_iterator< char> beg(in), end;
  35. std:: string strdata(beg, end);
  36. in.close();
  37. std:: regex word_regex("(<pic_url>)\\s*(http://.*)\\s*(</pic_url>)");
  38. auto words_begin = std::sregex_iterator(strdata.begin(), strdata.end(), word_regex);
  39. auto words_end = std::sregex_iterator();
  40. std:: cout << "Found " << std::distance(words_begin, words_end) << " words\n";
  41. for ( std::sregex_iterator i = words_begin; i != words_end; ++i) {
  42. std::smatch match = *i;
  43. std:: cout << " " << match.str() << '\n';
  44. }
  45. //正则捕获
  46. std:: string reg_str("<pic_url>\\s*(http://.*)\\s*</pic_url>");
  47. VSS vss;
  48. regex_search_all(strdata,vss,reg_str);
  49. for( auto kv : vss)
  50. {
  51. std:: cout<<kv.first<< '\t'<<kv.second<< '\n';
  52. }
  53. std:: regex url_regex(reg_str);
  54. std::smatch m;
  55. while( std::regex_search(strdata,m,url_regex))
  56. {
  57. for( auto beg = m.begin(); beg != m.end();beg++)
  58. {
  59. std:: cout<< "匹配上:"<<beg->str()<< "\n";
  60. }
  61. strdata = m.suffix().str();
  62. }
  63. //正则替换
  64. std:: regex long_word_regex("(\\w{7,})");
  65. std:: string new_s = std::regex_replace(s, long_word_regex, "[$&]");
  66. std:: cout << new_s << '\n';
  67. }

代码2 #include #include #include


   
   
  1. int main()
  2. {
  3. std:: string fnames[] = { "foo.txt", "bar.txt", "baz.dat", "zoidberg"};
  4. std:: regex pieces_regex("([a-z]+)\\.([a-z]+)");
  5. std::smatch pieces_match;
  6. for ( const auto &fname : fnames) {
  7. if ( std::regex_match(fname, pieces_match, pieces_regex)) {
  8. std:: cout << fname << '\n';
  9. for ( size_t i = 0; i < pieces_match.size(); ++i) {
  10. std::ssub_match sub_match = pieces_match[i];
  11. std:: string piece = sub_match.str();
  12. std:: cout << " submatch " << i << ": " << piece << '\n';
  13. }
  14. }
  15. }
  16. }

输出


   
   
  1. foo .txt
  2. submatch 0: foo .txt
  3. submatch 1: foo
  4. submatch 2: txt
  5. bar .txt
  6. submatch 0: bar .txt
  7. submatch 1: bar
  8. submatch 2: txt
  9. baz .dat
  10. submatch 0: baz .dat
  11. submatch 1: baz
  12. submatch 2: dat

c++11 中vector 的新用法

修正过剩的容量


   
   
  1. #include <vector>
  2. #include <iostream>
  3. void fun_old()
  4. {
  5. const int NUM = 1000;
  6. std:: vector< int*> vec( NUM, nullptr );
  7. for( auto& e : vec)
  8. {
  9. e = new int( 42);
  10. }
  11. std:: cout << "origin capacity: " << vec.capacity() << std:: endl;
  12. std:: cout << "first elem addr is " << vec[ 0] << std:: endl;
  13. for( auto it = vec.begin() + 2; it != vec.end() ; it++)
  14. {
  15. delete *it;
  16. *it = nullptr;
  17. }
  18. vec.erase(vec.begin() + 2, vec.end());
  19. std:: vector< int*>( vec ).swap( vec );
  20. std:: cout << "capacity after erase: " << vec.capacity() << std:: endl;
  21. std:: cout << "first elem addr is " << vec[ 0] << std:: endl;
  22. for( auto e : vec)
  23. {
  24. delete e;
  25. }
  26. }
  27. void fun_new()
  28. {
  29. const int NUM = 1000;
  30. std:: vector< int*> vec( NUM, nullptr );
  31. for( auto& e : vec)
  32. {
  33. e = new int( 42);
  34. }
  35. std:: cout << "origin capacity: " << vec.capacity() << std:: endl;
  36. std:: cout << "first elem addr is " << vec[ 0] << std:: endl;
  37. for( auto it = vec.begin() + 2; it != vec.end() ; it++)
  38. {
  39. delete *it;
  40. *it = nullptr;
  41. }
  42. vec.erase( vec.begin() + 2, vec.end() );
  43. vec.shrink_to_fit();
  44. std:: cout << "capacity after erase: " << vec.capacity() << std:: endl;
  45. std:: cout << "first elem addr is " << vec[ 0] << std:: endl;
  46. for( auto e : vec)
  47. {
  48. delete e;
  49. }
  50. }
  51. int main()
  52. {
  53. fun_old();
  54. fun_new();
  55. }

直接构造元素


   
   
  1. #include <vector>
  2. #include <string>
  3. #include <iostream>
  4. using namespace std;
  5. class Person
  6. {
  7. public:
  8. Person( string name ) : name_( name ) { }
  9. Person( const Person &other )
  10. : name_( other.name_ ) {
  11. cout << "in copy constructor with name is " << name_ << endl;
  12. }
  13. Person(Person&& other)
  14. : name_( std::move(other.name_))
  15. {
  16. cout << "in move constructor with name is " << name_ << endl;
  17. }
  18. private:
  19. string name_;
  20. };
  21. int main()
  22. {
  23. std:: vector<Person> vec;
  24. vec.reserve( 10 );
  25. cout<< "vec.push_back(Person(\"senlin\" ) )\n";
  26. vec.push_back( Person( "senlin" ) );
  27. cout<< "vec.push_back( p )\n";
  28. Person p( "zongming" );
  29. vec.push_back( p );
  30. cout<< "vec.push_back(Person(\"zhaoxiaobiao\"))\n";
  31. vec.push_back(Person( "zhaoxiaobiao"));
  32. cout<< "vec.push_back(std::move(p))\n";
  33. vec.push_back( std::move(p));
  34. vec.push_back( std::move(Person( "move")));
  35. cout<< "vec.emplace_back(\"zhaoxiaobiao\")\n";
  36. vec.emplace_back( "zhaoxiaobiao");
  37. }

虽然华丽,但也让人眼花缭乱。

虽然华丽,但也让人眼花缭乱。

【广告】 我的博客地址

            </div>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值