C++11新特性,部分代码整理来自网络,编译测试为VS2015。

#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <thread>
#include <future>
#include <algorithm>
#include <unordered_map>
#include <regex>

// auto
void cpp11_auto()
{
    // auto关键字,自动类型

    // 32位整数
    auto i = 100;
    printf("auto i = %d\n", i);
    
    // 64位整数
    auto j = 100000000000LL;
    printf("auto j = %lldLL\n", j);

    // 结构体
    struct Data { int data; };
    auto p = new Data();
    p->data = 234234;
    printf("auto p = new Data(), p->data = %d.\n", p->data);
    delete p;

    // 容器
    std::map<std::string, int> kv;
    kv["k1"] = 1;
    kv["k2"] = 2;
    kv["k3"] = 3;
    for(auto it = begin(kv); it != end(kv); it ++)
    {
        printf("<%s, %d>\n", it->first.c_str(), it->second);
    }
}

// loops
void cpp11_loops()
{
    // 区间迭代
    std::vector<int> sv;
    sv.push_back(100);
    sv.push_back(200);
    sv.push_back(300);
    for(int &v : sv)
    {
        printf("v = %d\n", v);
    }
    for(auto v : sv)
    {
        printf("auto v = %d\n", v);
    }

    std::map<std::string, int> kv;
    kv["k1"] = 1;
    kv["k2"] = 2;
    kv["k3"] = 3;
    for(const auto &it : kv)
    {
        printf("<%s, %d>\n", it.first.c_str(), it.second);
    }
}

// enum
void cpp11_enum()
{
    // 强类型枚举
    enum class Options { None, One, Two, Three, All };
    Options o1 = Options::All;
    Options o2 = Options::Two;
}

// Lambda
void cpp11_lambda()
{
    {
        // 基本Lambda语法
        auto func = [](int i, const std::string &s) { printf("%d, %s\n", i, s.c_str()); };
        func(100, "lambda");
    }
    {
        // 变量捕获 1
        int i = 10000;
        auto func = [&](const std::string &s) { printf("%d, %s\n", i, s.c_str()); };
        func("lambda");
    }
    {
        // 变量捕获 2
        class C
        {
        public :
            C() { a = 1111; }
            void f(int b)
            {
                auto func = [&](const std::string &s) { printf("%d, %d, %s\n", a, b, s.c_str()); };
                func("lambda");
            }
        private:
            int a;
        };

        C c;
        c.f(44444);
    }
    {
        // 返回值
        auto func1 = [](int i) { return i*100; };
        int ret1 = func1(1);

        auto func2 = [](int i) -> int { return i*10000; };
        int ret2 = func2(2);
    }

    {
        // for_each
        std::vector<int> v;
        v.push_back(100);
        v.push_back(200);
        v.push_back(300);
        std::for_each(std::begin(v), std::end(v), [](int n) { printf("%d\n", n); });

        auto func = [](int n) { return n == 100; };
        auto value = std::find_if(std::begin(v), std::end(v), func);
        if(value != std::end(v))
        {
            printf("value = %d\n", *value);
        }
        else
        {
            printf("not found\n");
        }
    }
/*
    []        不捕获任何变量
    [&]       以引用方式捕获所有变量
    [=]       用值的方式捕获所有变量(可能被编译器优化为const &)
    [=, &foo] 以引用捕获foo, 但其余变量都靠值捕获
    [bar]     以值方式捕获bar; 不捕获其它变量
    [this]    捕获所在类的this指针
*/
}

// mutex & atomic
void cpp11_mutex_atomic()
{
    // 互斥量和原子变量
    int value = 1000;
    std::recursive_mutex mutex1;
    {
        mutex1.lock();
        value = 20000;
        mutex1.unlock();
    }
    {
        std::lock_guard<std::recursive_mutex> lock(mutex1);
        value -= 200;
    }
    {
        std::unique_lock<std::recursive_mutex> lock(mutex1);
        value += 200;
    }

    std::recursive_timed_mutex mutex2;
    {
        if(mutex2.try_lock_for(std::chrono::milliseconds(200)))
        {
            mutex2.lock();
            printf("lock.\n");
            mutex2.unlock();
        }
    }
/*
    std::mutex                      最基本的 Mutex 类。
    std::recursive_mutex            递归 Mutex 类。
    std::time_mutex                 定时 Mutex 类。
    std::recursive_timed_mutex      定时递归 Mutex 类。
*/
    // 原子变量
    std::atomic<int>  a = 1000;
    std::atomic<bool> b = true;
    a ++;
    b = false;
}

// condition
static std::mutex               sm;
static std::condition_variable  sc;

void a_thread()
{
    std::unique_lock<std::mutex> lock(sm);
    printf("thread - waiting signal...\n");
    sc.wait(lock);
    printf("thread - received signal...\n");

    std::this_thread::sleep_for(std::chrono::milliseconds(2000));

    lock.unlock();
    printf("thread - notify signal...\n");
    sc.notify_one();
}

void cpp11_condition()
{
    std::thread at(a_thread);
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    printf("main - notify signal...\n");
    sc.notify_one();
    {
        std::unique_lock<std::mutex> lock(sm);
        sc.wait(lock);
        printf("main - received signal...\n");
    }

    at.join();
    printf("main - thread exit...\n");
}

// thread
void thread_proc(int a)
{
    printf("a = %d\n", a);
}

void cpp11_thread()
{
    std::thread threads[5];
    for(int i = 0; i < 5; i ++)
    {
        threads[i] = std::thread(thread_proc, i);
    }
    for(auto& t : threads)
    {
        t.join();
    }
}

int future_proc(int a)
{
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return a;
}

void cpp11_future()
{
    std::future<int> f = std::async(std::launch::async, future_proc, 100);
    if(f.valid())
    {
        std::future_status status = f.wait_for(std::chrono::milliseconds(100));
        if(status == std::future_status::ready)
        {
            // block until ready then return the stored result
            int a = f.get();
            printf("status is ready, return %d\n", a);
        }
        else
        {
            printf("status is %s\n", (status == std::future_status::timeout) ? "timeout" : "deferred");
        }
    }

    {
        // 包装一个可调用的对象,异步获取调用结果
        std::packaged_task<int()> task([]() { return 100; });
        std::future<int> result = task.get_future();
        std::thread(std::move(task)).detach();
        int value = result.get();
    }
}

void cpp11_override_final()
{
    struct Base
    {
        virtual int foo1(int a)
        {
            return a;
        }
        virtual int foo2(int a) final
        {
            return a;
        }
    };

    struct Sub1Class final : Base
    {
        virtual int foo1(int a) override
        {
            return a * 2;
        }
        // virtual int foo2(int a) override { return a * 2; } // 非法, Base的foo2函数已是final
        // virtual int foo5(float) override { return 0; }     // 非法, 父类没有此虚函数
    };

    // class Sub2Class : Sub1Class {}; // 非法, Sub1Class 已 final
}

void cpp11_regex()
{
    std::string fnames[] = { "foo.txt", "bar.txt", "bar.exe", "test", "a0bc.txt", "AAA.txt" };
    {
        std::regex base_match("[a-z]+\\.txt");
        for(const auto &fname : fnames)
        {
            bool ret = std::regex_match(fname, base_match);
            printf("%s:%s\n", fname.c_str(), ret ? "true" : "false");
        }
    }
    {
        std::regex base_regex("([a-z]+)\\.txt");
        for(const auto &fname : fnames)
        {
            std::smatch base_match;
            bool ret = std::regex_match(fname, base_match, base_regex);
            if(ret)
            {
                // sub_match 的第一个元素匹配整个字符串
                // sub_match 的第二个元素匹配了第一个括号表达式
                if(base_match.size() == 2)
                {
                    printf("sub-match[0] : %s, sub-match[1] : %s\n",
                        base_match[0].str().c_str(), base_match[1].str().c_str());
                }
            }
        }
    }
}
void cpp11_others()
{
    {
        // std::this_thread::yield() 当前线程让出自己的CPU时间片(给其他线程使用) 
        // std::this_thread::sleep_for() 休眠一段时间.
        std::atomic<bool> ready(false);
        while(!ready)
        {
            // std::this_thread::yield();
            for(int i = 0; i < 5; i ++)
            {
                std::this_thread::sleep_for(std::chrono::milliseconds(100));
            }
            ready = true;
        }
    }

    {
        // high resolution clock
        std::chrono::time_point<std::chrono::high_resolution_clock> ct1 = std::chrono::high_resolution_clock::now();
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        std::chrono::time_point<std::chrono::high_resolution_clock> ct2 = std::chrono::high_resolution_clock::now();

        int64_t systemClock1 = std::chrono::duration_cast<std::chrono::milliseconds>(ct1 - std::chrono::time_point<std::chrono::high_resolution_clock>()).count();
        int64_t systemClock2 = std::chrono::duration_cast<std::chrono::milliseconds>(ct2 - std::chrono::time_point<std::chrono::high_resolution_clock>()).count();

        int64_t sleepMS = std::chrono::duration_cast<std::chrono::milliseconds>(ct2 - ct1).count();
        int64_t sleepUS = std::chrono::duration_cast<std::chrono::microseconds>(ct2 - ct1).count();

        std::cout << "sleep milliseconds : " << sleepMS << ", sleep microseconds : " << sleepUS << std::endl;
    }

    {
        // 元组
        auto t1 = std::make_tuple(10, "string", 3.14);
        printf("tuple : %d, %s, %.3f\n", std::get<0>(t1), std::get<1>(t1), std::get<2>(t1));
        std::get<1>(t1) = "text";
        // 对tuple解包
        int v1;
        std::string v2;
        double v3;
        std::tie(v1, v2, v3) = t1;
        printf("tie(%d, %s, %.3f)\n", v1, v2.c_str(), v3);

        std::tuple<double, std::string> t2(3.1415926, "pi");
    }

    {
        // std::unordered_map, std::unordered_set

        std::map<std::string, int> m1;
        m1["b"] = 2;
        m1["c"] = 3;
        m1["a"] = 1;
        for(const auto &v : m1)
        {
            std::cout << v.first << ":" << v.second << std::endl;
        }
        std::unordered_map<std::string, int> m2;
        m2["b"] = 2;
        m2["c"] = 3;
        m2["a"] = 1;
        for(const auto &v : m2)
        {
            std::cout << v.first << ":" << v.second << std::endl;
        }
    }

    {
        auto x = 1;
        auto y = 2;
        // 推导返回类型
        decltype(x + y) z; // int
        z = 100;
        std::cout << z << std::endl;
    }

    {
        std::vector<int> v = {1, 2, 3, 4};
    }
    {
        // 原始字符串字面量
        std::string str = R"(C:\\What\\The\\Fxxksdfsadf345'''23'47523*"/'\\"\"")";
        std::cout << str << std::endl; // C:\\What\\The\\Fxxksdfsadf345'''23'47523*"/'\\"\""

        // 支持3种UNICODE编码: UTF-8, UTF-16, 和 UTF-32
        const char     u1[] = u8"I'm a UTF-8 string.\u2018";
        const char16_t u2[] = u"This is a UTF-16 string.\u2018";
        const char32_t u3[] = U"This is a UTF-32 string.\U00002018";
    }

    {
        // to string or wstring
        std::cout << std::to_string(1000) << ", " << std::to_string(3.1352345) << std::endl;
    }
    {
        typedef void(*FunctionType)(double);   // 老式语法
        using FunctionType = void(*)(double);  // 新式语法
    }
}

int main(int argc, char *argv[])
{
    cpp11_auto();

    cpp11_loops();

    cpp11_enum();

    cpp11_lambda();

    cpp11_mutex_atomic();

    cpp11_condition();

    cpp11_thread();

    cpp11_future();

    cpp11_regex();

    cpp11_others();

    return 0;
}

标签: none

已有 2 条评论

  1. 1 1

    555

  2. xiaohu xiaohu

    Hello.请问可以留个联系方式吗?有问题想请教一下.

添加新评论