1. 智能指针
作用:堆内存指针+引用计数(控制器,由默认的释放规则,可以自定义),用于堆内存管理,当对象离开生命周期时,引用计数降至为0,释放堆内存。
- 智能指针由3类
std::shared_ptr, std::unique_ptr, std::weak_ptr
- std::shared_ptr初始化
std::shared_ptr pShared1;
std::shared_ptr pShared2(nullptr); // 空智能指针
std::shared_ptr pSharedA(new int(10));
std::shared_ptr pSharedB = std::make_shared<int>(10);
std::shared_ptr pSharedC(new int[3],[](int* p) {delete []p;});
- std::shared_ptr拷贝构造
char * pTemp = new int(10);
std::shared_ptr pA(pTemp);
std::shared_ptr pB(pA); // 拷贝构造
- std::shared_ptr移动构造
char * pTemp = new int(10);
std::shared_ptr pA(pTemp);
std::shared_ptr pB(std::move(pA)); // 移动构造
std::shared_ptr pB = std::move(pA); // 移动构造
- 自定义释放规则
// 自定义释放规则
void deleteInt(int *p) {
delete[] p;
}
std::shared_ptr<int> p(new int[10], deleteInt);
std::shared_ptr<int> p2(new int[10], [](int *p){delete[] p;});
- 示例
#include <iostream>
#include <memory>
using namespace std;
int main() {
std::shared_ptr<int> p1(new int(10));
std::shared_ptr<int> p2(p1);
// 输出p2指向的数据
std::cout << *p2 << endl;
p1.reset(); // 引用计数减1, p1为空智能指针
if (p1) {
std::cout << "p1不为空" << std::endl;
} else {
std::cout << "p1为空" << std::endl;
}
// 以上操作,并不会影响p2
std::cout << *p2 << std::endl;
std::cout << p2.use_count() << std::endl;
return 0;
}
2. std::move将左值强制转换为右值
#include <iostream>
class moveDemo {
public:
// 构造函数
moveDemo() : num(new int(0)){
std::cout << "construct" << std::endl;
}
// 移动构造
moveDemo(const moveDemo &&d) : num(d.num) {
d.num = null;
std::cout << "move construct" << std::endl;
}
private:
int * num;
}
int main()
{
moveDemo demo;
std::cout << "demo2: " << std::endl;
moveDemo demo2(demo); // moveDemo demo2 = demo; 拷贝构造
std::cout << "demo3: " << std::endl;
moveDemo demo3(std::move(demo)); // 移动构造,此时demo.num为空指针
// moveDemo demo3 = std::move(demo);
return 0;
}
/* 程序运行结果如下:
construct!
demo2:
copy construct!
demo3:
move construct!
*/
3. 右值引用
int num = 10; // num为左值
int &&a = 10; // a为右值引用
a = 100; // 右值引用可以修改右值
std::cout << "a = " << a << std::endl;
/**
程序书结果为a = 100;
*/
4. for基于范围的循环
int arr[] = {1, 5, 2, 3, 7};
for (auto item : arr) {
std::cout << item << std::endl;
}
5. auto,decltype类型推导
auto var = value; // 基于变量的值,进行类型推导
decltype(expr) var = value; // 基于表达式expr,进行类型推导
6. using定义别名
typedef unsigned int myuint_t;
using myuint_t = unsigned int;
7. 匿名函数
[外部变量访问方式说明符](入参) -> 返回值 {
// 函数体
}
8. 模板函数,支持默认模板参数
template <typename R = int, typename U>
R func(U val) {
return val;
}
int main() {
func(97); // R = int, U = int
func<char>(97); // R = char, U = int
func<double, int>(97); // R = double, U = int
return 0;
}