后端技术_智能指针_正则表达式
最近更新:2024-09-23
|
字数总计:1.1k
|
阅读估时:4分钟
|
阅读量:次
- 智能指针
- shared_ptr
- unique_ptr
- weak_ptr
- 右值引用与移动语义
- 匿名函数lambda
智能指针
shared_ptr
- 智能指针是不是线程安全的?
- 引用计数是线程安全的(原子计数)
- 指向的内容是线程不安全的,需要自己添加锁机制
1 2 3 4 5 6 7 8 9 10
| auto sp1 = make_shared<int>(100);
shared_ptr<int> sp2(new int(100));
std::shared_ptr<int> p2; p1.reset(new int(1)); p1.reset(); if(p1){ }
|
- 指定删除器
1 2 3 4 5 6 7 8 9 10 11 12 13
| ##include <iostream> ##include <memory> using namespace std; void DeleteIntPtr(int *p) { cout << "call DeleteIntPtr" << endl; delete p; } int main() { std::shared_ptr<int> p(new int(1), DeleteIntPtr); return 0; }
|
- 同一个裸指针不要托管给两个智能指针
1 2 3 4 5 6
| int *ptr = new int; shared_ptr<int> p1(ptr); shared_ptr<int> p2(ptr); cout << "p1.use_count()= " << p1.use_count() << endl; cout << "p2.use_count()= " << p2.use_count() << endl;
|
- 不要在函数实际参数中创建智能指针
1 2 3 4
| function(shared_ptr<int>(new int), g());
shared_ptr<int> p(new int); function(p, g());
|
- 不要返回shared_ptr(this),使用shared_from_this();
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class A { public: shared_ptr<A> GetSelf(){ return shared_ptr<A>(this); } ~A(){ cout << "Destructor A" << endl; } } int main(){ shared_ptr<A> sp1(new A); shared_ptr<A> sp2 = sp1->GetSelf(); return 0; }
|
- 避免循环引用
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
| class A; class B; class A{ public: std::shared_ptr<B> bptr; ~A(){ cout << "A is deleted" << endl; } } class B{ public: std::shared_ptr<A> aptr; ~B(){ cout << "B is deleted" << endl; } } int main(){ { std::shared_ptr<A> ap(new A); std::shared_ptr<B> bp(new B); ap->bptr = bp; bp->aptr = ap; } cout << "main leave " << endl; return 0; }
|
unique_ptr
weak_ptr
- 用于避免循环引用,需要结合shared_ptr使用
- 使用前一定要检查合法性
1 2 3 4 5 6 7 8
| weak_ptr<int> wp; { shared_ptr<int> sp(new int(1)); wp = sp; shared_ptr<int> sp_ok = wp.lock(); } shared_ptr<int> sp_null = wp.lock();
|
右值引用与移动语义
- 左值——取地址,位于等号左边;右值——不可取地址,位于等号右边;
- 右值引用
1 2 3
| int &&ref = 5; int a = 4; int &&ref2 = a;
|
- std::move——将左值强制转换成右值
1 2 3 4 5 6 7 8 9 10 11 12
|
int temp = 5; int &&ref_a = std::move(temp); ref_a = 6; cout << "temp==" << temp << endl;
|
- 完美转发forward
- emplace_back原理
匿名函数lambda
1 2 3 4 5 6 7 8 9 10 11
|
auto Add = [](int a, int b) -> int{ return a+b; }; std::cout << Add(1,2) << endl;
|
- 泛型lambda(C++14以后)
1 2 3 4 5
| auto add = [auto x, auto y]{ return x + y; }; std::cout << add(1, 2) << std::endl; std::cout << add(1.1, 1.2) << std::endl;
|
2024-03-30
该篇文章被 Cleofwine
归为分类:
服务端