std::function
std::function的实例可以对任何可以调用的目标实体进行存储、复制和调用操作。这些目标实体包括普通函数、Lambda表达式、函数指针以及其它函数对象等。(升级版函数指针)
//普通函数
int MyFunc1(int a,int b){
}
function<int(int,int)> functor1 = MyFunc1;
functor1(7,2);
//lambda
auto MyFunc2 =[](int a,int b){
return a + b;};
function<int(int,int)> functor2 = MyFunc2;
functor2(2,5);
//仿函数
struct MyFunc3{
int operator() (int a,int b){
}
};
function<int(int,int)> functor3 = MyFunc3;
functor2(2,9);
智能指针
new分配内存,智能指针可以自动释放。而传统指针需要手动delete。
智能指针对普通的指针进行封装,负责自动释放所指的对象,这样的一层封装机制的目的是为了使得智能指针可以方便的管理一个对象的生命期。
- auto_ptr(c++11弃用)
auto_ptr<string> p1(new string("I reigned loney as a cloud."));
auto_ptr<string> p2;
p2=p1; //auto_ptr不会报错
此时p2剥夺p1所有权。访问p1会报错。(存在内存崩溃的风险)
-
unique_ptr
实现独占式拥有或严格拥有概念,保证同一时间内只有一个智能指针可以指向该对象。避免资源泄露
unique_ptr<string> p3(new string("I reigned loney as a cloud."));
unique_ptr<string> p4;
p4 = p3; //error
/*****************************
当将一个 unique_ptr 赋值给另一个
如果源 unique_ptr 是个临时右值
编译器允许这么做
否则 报错
*****************************/
unique_ptr<string> ps1, ps2;
ps1 = make_unique<int>(200);
ps2 = move(ps1);
-
shared_ptr
实现共享式拥有概念。多个智能指针可以指向相同对象,该对象和其相关资源会在“最后一个引用被销毁”时候释放。用计数机制来表明资源被几个指针共享。
多个线程同时读同一个shared_ptr对象是线程安全的,但是如果是多个线程对同一个shared_ptr对象进行读和写,则需要加锁。
多线程读写shared_ptr所指向的同一个对象,不管是相同的shared_ptr对象,还是不同的shared_ptr对象,也需要加锁保护。shared_ptr拥有成员函数如下:
- use_count — 引用计数的个数
- unique — 是否独占
- swap — 交换两个shared_ptr所拥有的对象
- get — 返回内部对象
-
weak_ptr
- 尝尝与shared_ptr搭配使用,为shared_ptr的观察者。
- 不控制对象生命周期的智能指针, 它指向一个 shared_ptr 管理的对象。
- 当 shared_ptr 管理的资源被释放时,weak_ptr 会自动变成 nullptr。
- 只是提供了对管理对象的一个访问手段。用来解决shared_ptr相互引用时的死锁问题
类型转换
const_cast
— 将const type
转化为type
(type为指针或引用)static_cast
— 可以用于各种编译器认可的隐式转换(类对象向上转换)dynamic_cast
— 用于含有虚函数的类的转换,用于类向上和向下转换reinterpret_cast
— 任意类型转换,不保证成功。
//static_cast
int a = 5;
double b = static_cast<int>(a);
class Base{
};
class Derive:Base{
};
Base* ptr;
Derive *temp = new Derive();
ptr = static_cast<Base*>(temp);
//const_cast
const int a = 1;
int *p = const_cast<int*>(&a);
Variadic Template
数量不定的模板参数。
...
用来表示一包pack
。表示模板参数、函数参数、函数参数类型的数量不确定。(用来递归)
void print() {
}//递归出口
template<typename T,typename... Types>
void print(constT& firstArg,const Types&... args) {
cout <<firstArg<<endl;
print(args...);
//sizeof...(args)可以知道当前剩余几个
}
//tuple
template<typename... Values>class tuple;
template<> class typle<>{
};
template<typename Head,typename... Tail>
class tuple<Head,Tail...>
:private tuple<Tail...>
{