0
点赞
收藏
分享

微信扫一扫

C++11


auto
auto不能作为函数的参数,后续C++20 可以了
auto 不能作用于类的非静态成员变量
auto 关键字不能定义数组
auto 不能作用于模板参数

std::less<int> ()用法

auto lessFun = std::less<int>(); //是struct 对象,重载了()作为比较函数
bool bRes = lessFun(1, 8);
int foo[]={10,20,5,15,25};
std::sort (foo, foo+5, std::less<int>()); // 5 10 15 20 25
for(int i = 0; i< 5; i++)
{
std::cout << "value:"<<foo[i]<<std::endl;
}

//bind1st 把 x 作为 fn 的第一个参数,bind2nd 把 x 作为 fn 的第二个参数
//这里把10作为less()的第二个参数,11是第一个参数
auto is_large_ten = std::bind2nd(std::less<int>(), 10);
bool bRes = is_large_ten(11);

std::thread

#include <thread>
#include <exception>
#include <mutex>
#include <random>


void ReqTestFun(int i)
{
cout << "will mutex" << endl;

//std::mutex myMutex;
//try
//{
// myMutex.lock();
//}
//catch(std::exception& e)
//{
// cout << "catch" << endl;
//}
//myMutex.unlock();

CHttpRequest httpRequest("http://127.0.0.1:8080/spaces");
string strResData;
char szMsg[1024] = { '\0' };
sprintf_s(szMsg, "{\"age\" : \"%d\"}", i);
httpRequest.PostData(szMsg, strResData);

};

int main()
{
InitHttp();
for (int i = 0; i < 50; i++)
{
std::thread thReqTest(ReqTestFun, i);
thReqTest.join(); //不join的话,会有异常
}

//ReqTestFun(5);
char chIn;
cin >> chIn;
}

单例模式线程安全

在c++11中,static静态类对象在执行构造函数进行初始化的过程是线程安全的

g++ hello.cpp -o hello -std=c++11 -lpthread
 

#include <thread>
#include <exception>
#include <mutex>
#include <random>
#include <iostream>
#include <windows.h>
using namespace std;


void ReqTestFun(int i)
{
cout <<i << " will mutex" << endl;
Sleep(3000000);
cout << i << " end mutex" << endl;

//std::mutex myMutex;
//try
//{
// myMutex.lock();
//}
//catch(std::exception& e)
//{
// cout << "catch" << endl;
//}
//myMutex.unlock();



};

int main()
{

for (int i = 0; i < 50; i++)
{
std::thread thReqTest(ReqTestFun, i);
thReqTest.detach(); //不join的话,会有异常
}

//ReqTestFun(5);
char chIn;
cin >> chIn;
}

std::move

并不能进行深拷贝, 原对象不再被使用,如果对其使用会造成不可预知的后果。

智能指针(不要混合使用普通指针和智能指针)

unique_ptr

void Unique_Test()
{
unique_ptr<Device> upDev(new Device);
upDev->m_strName = "xiaoming";
upDev->InitDevice();
unique_ptr<Device> upOther = move(upDev); //upDev会被置空empty
upOther->m_strName = "xiaozhang";

//Device* pDev = upDev.release(); //不会释放原来对象, 对象自己手动释放了,否则内存泄漏
//upDev.reset(); //会释放原来对象
//Device* pDev = upDev.get();
//pDev->m_strName = "xiaozhang";
}

lambda表达式

mutable:默认情况下,lambda函数总是一个const函数,捕捉的传值参数具有常性,mutable可以取消常性。使用mutable修饰符时,参数列表不能省略,即使参数为空

void TestLambda() {
//最简单的lambda,没有参数,()和 -> 返回值,mutable都可以省略
auto fun0 = [] {
cout << "测试" << endl;
};
fun0();
int x = 100;
int y = 50;

auto fun1 = [&x, y] () -> int {
x += 1;
return 0;

};
fun1();

auto fun2 = [x, y]() mutable -> int {
x += 1; //必须加mutable
return 0;

};
fun2();

}

举报

相关推荐

c++11 tuple

C++11 异常

【C++】C++11

C++11 【初识】

C++11(下)

c++11 noexcept

c++11上篇

C++——C++11

0 条评论