c++特性

c++ 11

Lambda expressions

1
2
3
4
// []() -> T {}

auto g = [](int x){return x * x;};
std::cout << g(3); // 9

作为predict

1
2
std::vector<int> s = {1, 2, 3, 5};
std::cout << std::all_of(s.begin(), s.end(), [](int x) { return x > 0;}) << "\n"; // 1

range-based for loop

1
2
3
4
5
6
// for( range_declaration: range_expression) loop statement

std::vector<int> s = {1, 2, 3, 4};
for(auto& i : s){
std::cout << i << std::endl;
}

functor

A functor (or function object) is a C++ class that acts like a function. Functors are called using the same old function call syntax. To create a functor, we create a object that overloads the operator().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// C++ program to demonstrate working of 
// functors.
#include <bits/stdc++.h>
using namespace std;

// A Functor
class increment
{
private:
int num;
public:
increment(int n) : num(n) { }

// This operator overloading enables calling
// operator function () on objects of increment
int operator () (int arr_num) const {
return num + arr_num;
}
};

int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
int to_add = 5;

transform(arr, arr+n, arr, increment(to_add));

for (int i=0; i<n; i++)
cout << arr[i] << " ";
}

unique_ptr

参考链接

每一个unique_ptr与一个raw_ptr绑定,当unique_ptr out of scope, 会释放raw_ptr分配的内存

特点

  • 无法copy或者assign,只能在unique_ptr之间用std::move进行移动
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <memory>

struct Task
{
int mId;
Task(int id ) :mId(id)
{
std::cout<<"Task::Constructor"<<std::endl;
}
~Task()
{
std::cout<<"Task::Destructor"<<std::endl;
}
};

int main()
{
// Create a unique_ptr object through raw pointer
std::unique_ptr<Task> taskPtr(new Task(23));
// auto taskPtr = new Task(23); //leak
//Access the element through unique_ptr
int id = taskPtr->mId;

std::cout<<id<<std::endl;


return 0;
}

shared_ptr/weak_ptr