首页 > 编程语言 > 详细

C++11新特性

时间:2019-05-12 23:47:31      阅读:140      评论:0      收藏:0      [点我收藏+]

1、统一的初始化方法

技术分享图片
int arr[3]{1, 2, 3};
vector<int> iv{1, 2, 3};
map<int, string> mp{{1, "a"}, {2, "b"}};
string str{"Hello World"};
int * p = new int[20]{1,2,3};
struct A {
int i,j; A(int m,int n):i(m),j(n) { }
};
A func
(int m,int n ) { return
{m,n}; }
int main() { A * pa = new A {3,7}; }
统一的初始化方法

2、成员变量默认初始值

技术分享图片
class B {
public:
int m = 1234;
int n;
};
int main() {
B b
;
cout << b.m << endl; //输出 1234
return 0;
}
成员变量默认初始值

3、auto 关键字

4、decltype关键字

求表达式的类型

int i;
double t;
struct A { double x; };
const A* a = new A();
decltype(a) x1; // x1 is A *
decltype(i) x2; // x2 is int
decltype(a->x) x3; // x3 is double
decltype((a->x)) x4 = t; // x4 is double&

5、智能指针shared_ptr

头文件<memory>

通过shared_ptr的构造函数,可以让shared_ptr对象托管一个new运算符返回的指针。

shared_ptr<T> ptr(new T); // T 可以是 int ,char, 类名等各种类型

此后ptr就可以像 T* 类型的指针一样来使用,即 *ptr 就是用new动态分配的那个对象,而且不必操心释放内存的事。

多个shared_ptr对象可以同时托管一个指针,系统会维护一个托管计数。当无shared_ptr托管该指针时,delete该指针。

shared_ptr对象不能托管指向动态分配的数组的指针,否则程序运行会出错。

6、空指针nullptr

7、基于范围的for循环

#include <iostream>
#include <vector>
using namespace std;
struct A { int n; A(int i):n(i) { } };
int main() {
  int ary[] = {1,2,3,4,5};
  for(int & e: ary)
    e*= 10;
  for(int e : ary)
    cout << e << ",";
  cout << endl;
  vector<A> st(ary,ary+5);
  for( auto & it: st)
    it.n *= 10;
  for( A it: st)
    cout << it.n << ",";
  return 0;
}

 

8、右值引用和move语义

右值:一般来说,不能取地址的表达式就是右值, 能取地址的就是左值。主要目的是提高程序运行的效率,减少需要进行深拷贝的对象进行深拷贝的次数。

class A { };
A & r = A(); // error , A()是无名变量,是右值
A && r = A(); //ok, r 是右值引用

 

C++11新特性

原文:https://www.cnblogs.com/zhuzhudong/p/10850521.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!