添加右值引用相关测试代码

master
caiyuzheng 2021-03-13 00:46:52 +08:00
parent 1ed0fe6c1f
commit 9c139d745a
5 changed files with 61 additions and 14 deletions

View File

@ -3,6 +3,7 @@ project(cpp11)
message("current dir" ${CMAKE_CURRENT_SOURCE_DIR})
# set(CMAKE_CXX_FLAGS "-fno-elide-constructors")
aux_source_directory(. SOURCE)
message(info ${SOURCE})
add_executable(cpp11 ${SOURCE} )

View File

@ -7,7 +7,7 @@ using namespace std;
int main(){
std::cout<<"test start"<<endl;
try{
TestConditionVariable();
TestRValue();
}catch( std::exception e){
std::cout<<"exception"<<e.what();
}

View File

@ -92,10 +92,52 @@ int TestConditionVariable() {
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(do_print_id, i);
std::cout << "10 threads ready to race...\n";
go();
go();
for (auto & th:threads)
th.join();
return 0;
}
class TestClass
{
public:
TestClass() : num(new int(0))
{
std::cout << "construct!" << std::endl;
}
//拷贝构造函数
TestClass(const TestClass &d) : num(new int(*d.num))
{
std::cout << "copy construct!" << std::endl;
}
~TestClass()
{
std::cout << "class destruct!" << std::endl;
}
private:
int *num;
};
TestClass get_demo()
{
return TestClass();
}
int TestOptiomization()
{
TestClass a = get_demo();
return 0;
}
int TestRValue()
{
std::string str = "Hello";
std::vector<std::string> v;
//调用常规的拷贝构造函数,新建字符数组,拷贝数据
v.push_back(str);
std::cout << "After copy, str is \"" << str << "\"\n";
//调用移动构造函数掏空str掏空后最好不要使用str
v.push_back(std::move(str));
std::cout << "After move, str is \"" << str << "\"\n";
std::cout << "The contents of the vector are \"" << v[0];
}

View File

@ -1,4 +1,5 @@
#include <thread>
#pragma once
#include <cstdint>
#include <iostream>
#include <functional>
@ -6,8 +7,11 @@
#include <thread>
#include <chrono>
#include <cstdlib>
#include <vector>
void TestPromiseFutureBefore();
void TestThreadDetach();
void TestLockGuard();
int TestConditionVariable();
int TestOptiomization();
int TestRValue();

View File

@ -1,17 +1,16 @@
#include "threadpool.h"
// 参考于https://www.cnblogs.com/bigosprite/p/11071462.html
namespace general{
void work(general::CThreadPool *pool)
{
}
CThreadPool::CThreadPool(int num)
{
this->mThreadCnt = num;
mThreads.reserve(num);
for(int i = 0;i < num;i++){
std::thread *t = new std::thread(general::work,this);
this->mThreads.push_back(t);
mThreads.emplace_back(new std::thread(&ThreadPool::Process, this, i));
}
}
int CThreadPool::AddTask(Task *t){
if ( nullptr == t){
return -1;
@ -53,14 +52,15 @@ namespace general{
bool CThreadPool::Started(){
return this->mStarted;
}
CThreadPool::~CThreadPool(){
if(this->mStarted){
for (size_t i = 0; i != this->mThreads.size(); ++i)
{
// if (mThreads[i].joinable())
// {
// mThreads[i].join();
// }
if (mThreads[i]->joinable())
{
mThreads[i]->join();
}
}
}
}