C ++ 11 and c ++ 14 new features

https://www.jianshu.com/p/b8a36ff7ac27

1.nullptr

The purpose is to replace nullptr appears NULL, the traditional C ++ will NULL, 0 as the same thing. nullptr keyword, designed to distinguish between an empty pointer, 0. nullptr of type nullptr_t.

2.auto

auto and decltype two keywords to achieve a type inference, let the compiler worry about the type of the variable.

  • auto function can not be used for mass participation, consider the issue of overloading, we should use templates.
  • auto array type can not be used to derive

3. decltype

Declare the return type

 

template<typename T1,typename T2>
auto add(T1 x,T2 y) ->decltype(x+y);

Expression compiler analyzes and get its type, the actual value of the expression is not calculated.

 

auto x = 1;
auto y = 2;
decltype(x+y) z;

4.foreach

The original for loop

 

std::vector<int> arr(5, 100);
for(std::vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
{
             std::cout << *i << std::endl;
}

right now

 

for(auto &i:arr)
{
    std::cout << i << std::endl;
}

The initialization list

 

struct A
{
     int a;
     float b;
};
A a {1,1.0};
A b{};  //初始化为0,指针初始化为nullptr

initializer_list

 

#include <initializer_list>
class Magic {
public:
    Magic(std::initializer_list<int> list) {
        for(auto &i:list){

        }
    }
};

Magic magic = {1,2,3,4,5};
std::vector<int> v = {1, 2, 3, 4};
max({1,2,3,4});

6. Templates

Template variable parameters

 

void print()
{

}

template<typename T,typename... Types>
void print(const T&  firstArgs,const Types&... args){
    cout<<firstArgs<<endk;
    print(args...);
}

Type alias template

 

template< typename T, typename U, int value>
class SuckType {
public:
    T a;
    U b;
    SuckType():a(value),b(value){}
};

template <typename T>
using NewType = SuckType<int, T, 1>;    // 合法

The default template arguments

 

template<typename T = int, typename U = int>
auto add(T x, U y) -> decltype(x+y) {
    return x+y;
}

7. Constructor

Commission structure

Such a constructor constructor can call another constructor in the same class, so as to simplify object code

 

class Base {
public:
    int value1;
    int value2;
    Base() {
        value1 = 1;
    }
    Base(int value) : Base() {  // 委托 Base() 构造函数
        value2 = 2;
    }
};

Inheritance structure

There follows the parent class

 

class A
{
    A(int i) {}
    A(double d,int i){}
    A(float f,int i,const char* c){}
    //...等等系列的构造函数版本
}

Subclass inherits the original parent, need to explicitly call the parent class constructor, as follows:

 

class  B:A
{
    B(int i):A(i){}
    B(double d,int i):A(d,i){}
    B(folat f,int i,const char* c):A(f,i,e){}
    //......等等好多个和基类构造函数对应的构造函数
}

Now this:

 

class  B:A
{
    using A::A;
    //关于基类各构造函数的继承一句话搞定
}

8.Lambda

Lambda expressions, in fact, offers a similar feature of anonymous functions, and anonymous function is a function in need, but do not want the trouble to go on the naming of a function used.

Lambda expressions basic syntax is as follows:

 

[ caputrue ] ( params ) opt -> ret { body; };

1) capture是捕获列表; 
2) params是参数表;(选填) 
3) opt是函数选项;可以填mutable,exception,attribute(选填) 
mutable说明lambda表达式体内的代码可以修改被捕获的变量,并且可以访问被捕获的对象的non-const方法。 
exception说明lambda表达式是否抛出异常以及何种异常。 
attribute用来声明属性。 
4) ret是返回值类型(拖尾返回类型)。(选填) 
5) body是函数体。
  • Captures lists: a list of lambda expressions capture fine control of the external variables that can be accessed lambda expressions, and how to access these variables.

    1. [] Does not capture any of the variables.
    2. [&] Capture external scope all variables, and used as a reference in the body of the function (capture by reference).
    3. [=] To capture an external scope all variables and functions used in the body as a copy (by value capture). Note that the value captured on the premise that the variables can be copied, and the copy of the variable is captured when the lambda expression is created, rather than a copy when calling. If you want to lambda expressions when you call instant access to external variables, we should use the reference capture.
    4. [=, & Foo] to capture the value of all variables by external scope press capture foo reference variable.
    5. [Bar] by value capture bar variables at the same time does not capture other variables.
    6. [This] to capture this pointer to the current class, and allow lambda expressions have the same access to the current class member functions. If you have used or & =, you add this option by default. The purpose of this is captured using member functions and member variables in the current class in lamda.

9. container

  • array

std :: array stored in the stack memory, heap memory compared to the std :: vector, we have the flexibility to access these elements inside, resulting in higher performance. Create a fixed size array compile time, std :: array can not be converted implicitly to a pointer, using std :: array specify their type and size can, but must be used to specify the size of the constant expression.

 

std::array<int, 4> arr= {1,2,3,4};
int len = 4;
std::array<int, len> arr = {1,2,3,4}; // 非法, 数组大小参数必须是常量表达式
  • forward_list

std :: forward_list list is a container, method and use substantially similar std :: list.
And std :: list of different implementations of doubly linked list, std :: forward_list be achieved using one-way linked list, provides O (1) insert an element of complexity, does not support fast random access (this is the list of features), also standard library does not provide a unique vessel size () method of the container. When no bidirectional iteration :: list has a better space utilization than std.

  • Unordered container

    std::unordered_map/std::unordered_multimap 和 std::unordered_set/std::unordered_multiset。

    Unordered container elements are not sorted, be achieved by internal Hash table, average complexity for insertion and search elements O (constant).

  • tuple

std :: make_tuple: construction tuple

 

auto student=std::make_tuple(3.8, 'A', "张三");

std :: tie: tuple unpacking

 

std::tie(gpa, grade, name) = student;

std :: get: get the value of a tuple location

 

auto gpa=std::get<0>(student);

And a transition structure 10. The copy constructor

 

string a(x);                                         // line 1
string b(x + y);                                    // line 2
string c(some_function_returning_a_string());       // line 3

The first line (line 1) of the left x is a value (lvalues) using deep copy constructor, as follows:

 

string(const string& that)
{
    size_t size = strlen(that.data) + 1;
    data = new char[size];
    memcpy(data, that.data, size);
}

The second parameter is the right value of three lines, using a transfer constructors, as follows:

 

string(string&& that)   // string&& is an rvalue reference to a string
{
data = that.data;
that.data = 0;
}

Since the depth data is not copied heap memory, but only a copy pointer, and the pointer to the source object blanking. In fact, we "steal" the memory data belonging to the source object. Since the source object is an rvalue, it will not be used, and therefore the customer will not be aware of the source object is changed. Here, we did not really replicate, so we put this constructor is called "move constructor" (move constructor), his job is to shift resources from one object to another, instead of copying them. The compiler is based on parameter values of the left or right to choose values between the copy constructor and move constructor.

Copy constructor deep copy is performed, because the source object itself must not be changed. It can be transferred to copy constructor pointer, the pointer to the source object blanking, this form, which is safe, because the user can no longer use the object.

11.move left shift value

The standard library header files provide a template function std :: move <utility> in. In fact, std :: the Move is just simply convert the value to the left and right value, which itself did not transfer anything. It is just to let the object can be transferred.

unique_ptr only move constructor, as follows:

 

unique_ptr(unique_ptr&& source)   // note the rvalue reference
{
    ptr = source.ptr;
    source.ptr = nullptr;
}

Unique_ptr object of assignment:

 

unique_ptr<Shape> a(new Triangle);
unique_ptr<Shape> b(a);              // still an error
unique_ptr<Shape> c(std::move(a));   // okay

The second line can not compile, because a value is left, but the parameters unique_ptr && source can only accept the right value. The third line compiler is no problem, then the third line, no longer has a target, by a move to the right into a value.

12.explicit

Front constructor add explicit modification, this constructor can only be specified explicitly call / use, not as a type conversion operator is implicitly use. General constructor can be implicitly called. The explicit constructor can only be invoked explicitly.

13.=default / =delete

C ++ class has four special member functions, which are: default constructor, destructor, copy constructor and copy assignment operator.

  • The function is declared "= default" function, the compiler will be explicitly declared "= default" function automatically generating function thereof.
  • The statement after the function "= delete;", the function can be disabled.

14.using

  • Namespaces

      using namespace std;
    
  • statement

      using _basic::_M_allocate;
    
  • template

      template<typename T>
      using mystring=basic_string<T,char_traits<T>>;
    
  • Function pointer

      using func=void(*)(int,int);
    

15.noexcept

The condition is true nothrow

 

void foo() noexcept(true){

}

16.override

 

class base{
    virtual void func(float){

    }
}

class Devied:Base{
    virtual void func(float) override{
        //显示的声明为重写函数
    }
}

17.final

Acts on the class, the class can not be inherited represents

 

class Base final{

}

And the role of a virtual function, indicates that the virtual function can not be rewritten

 

class Base{
    virtual void f() final;
}

18. Smart Pointers

C ++ 11 introduced smart pointers, since then no longer need to manually release the memory. Smart pointer a pointer actually ordinary package (i.e., packaged as a class), and by overloading * -> two operators, so that the smart pointer like an ordinary pointer performance. shared_ptr / unique_ptr / weak_ptr

unique_ptr

Exclusive pointer, can not copy or assignment to another smart pointer can move transfer ownership

 

unique_ptr<Monster> monster1(new Monster());    //monster1 指向 一个怪物   
unique_ptr<Monster> monster2 = monster1;        //Error!编译期出错,不允许复制指针指向同一个资源。
unique_ptr<Monster> monster3 = move(monster1);  //转移所有权给monster3.   
monster1->doSomething();                    //Oops!monster1指向nullptr,运行期崩溃

shared_ptr

Shared_ptr pointing to the same place more resources, when all shared_ptr are all released, where the resource is not released. You can copy and assignment.

 

{
    shared_ptr<Monster> monster1(new Monster());   //计数加到1
    do{std::shared_ptr<Monster> monster2 = monster1;    //计数加到2
    }while(0);          
  //该栈退出后,计数减为1,monster1指向的堆对象仍存在
    shared_ptr<Monster> monster3 = monster1; //计数加到2
    shared_ptr<Monster> monster4 = monster1; //计数加到3
}
//该栈退出后,shared_ptr都释放了,计数减为0,它们指向的堆对象也能跟着释放.

weak_ptr

Shared_ptr is to assist exist, it only provides a means of access to managed objects, but also dynamically in real time to know whether the object pointed to survive. To create a weak pointer, you must already have the resources but is a shared pointer. weak_ptr can only be used to track a shared resource, but does not actually own, it will not hinder the release of resources. Before reading the shared resources you need to run lock, can be accessed after obtaining shared_ptr.

 

shared_ptr<Monster> monster1(new Monster());
weak_ptr<Monster> r_monster1 = monster1;
r_monster1->doSomething();  //Error! 编译器出错!weak_ptr没有重载* 和 -> ,无法直接当指针用
shared_ptr<Monster> s_monster1 = r_monster1.lock();//OK!可以通过weak_ptr的lock方法获得shared_ptr。

19.cast type conversion

static_cast

Built-in conversion between the basic data types, enum, struct, int, char, float, etc., related to the kind of thing, static_cast only be converted in an interconnected types, not necessarily contain virtual functions.

 

int c=static_cast<int>(7.987);

class A
{};
class B:public A
{};
class C
{};
 
int main()
{
    A* a=new A;
    B* b;
    C* c;
    b=static_cast<B>(a);  // 编译不会报错, B类继承A类
    c=static_cast<B>(a);  // 编译报错, C类与A类没有任何关系
    return 1;
}

const_cast

Only convert one of its role as a constant expression. It would not make a type of data into const const type or the attribute removed const.

 

  int a = 10;
  const int *p = &a;    // 被const修饰,不能使用该指针修改其指向内容的值  
  int *q;
  q = const_cast<int *>(p);     // 去除p的常量性给q,如果不去除直接赋值会报错 
  *q = 20; 

reinterpret_cast

Cast a very strong cast, which may be any two unrelated pointer or reference conversion

dynamic_cast

static_cast will conduct safety checks during compilation, and dynamic_cast will conduct security checks in the course of operation. Both are with security checks to prevent the wrong type conversion program leading to deviation.

Summary
static_cast will static security checks, generally used for switching between the built-in data types and conversion classes generally.
const_cast and is mainly used to remove a pointer const and volatile type of reference.
reinterpret_cast for conversion or no relationship between the reference pointer, such as pointer character pointer turn shaping.
dynamic_cast commonly used to convert between the base and derived classes.



Author: huifeiyu
link: https: //www.jianshu.com/p/b8a36ff7ac27
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Published 101 original articles · won praise 73 · views 120 000 +

Guess you like

Origin blog.csdn.net/usstmiracle/article/details/104059760