C/C++98/C++11

c++11特性

2019-02-22  本文已影响14人  爱吃花栗鼠的猫

std::function

将可调用的函数或者函数指针等,封装成类使用

std::bind

注意其参数是拷贝的方式,所以才有了std::ref

std::ref

配合std::bind使用的时候,以引用的方式传入

lambda function

匿名函数,使用起来比较方便

std::mutex

不可重入锁,可配合locker_guard使用

std::locker_guard

类似AutoLocker raii思想的一种体现,资源在构造函数中创建,然后生命周期结束的时候自动释放

std::unique_lock

std::once_flag

只用一次,配合std::call_once使用

std::call_once

只调用一次

static_assert

静态错误检测,可在编译器就检测错误

pthread_once

class noncopyable {
protected:
    constexpr noncopyable() = default;
    ~noncopyable() = default;
    noncopyable(const noncopyable &) = delete;
    noncopyable &operator= (const noncopyable &) = delete;
};

template <typename T>
class Singleton : noncopyable {
public:
    static T& instance(){
        pthread_once(&ponce_, &Singleton::init);
        return *value_;
    }

private:
    Singleton();
    ~Singleton();

    static void init() {
        value_ = new T();
    }

private:
    static pthread_once_t ponce_;
    static T* value_;
};

template <typename T>
pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT;

template <typename T>
T *Singleton<T>::value_ = NULL;

enable_shared_from_this

安全传递智能指针所有权

std::thread

可直接通过lambda赋值,非常方便

std::move

转移所有权,无内存拷贝

pthread_cond 条件变量

减少线程的浪费和等待,不要在用户态进行等待

using

定义别名

auto

省下了定义好长的一段命名

static_pointer_cast

实现shared_ptr之间的转换,基类不需要虚函数.

#include <memory>
#include <iostream>

class base{
public:
    base(){std::cout << "base" << std::endl;}
    ~base(){std::cout << "~base" << std::endl;}
    void print(){std::cout << "base::print" << std::endl;}
};

class derived:public base{
public:
    derived(){std::cout << "derived" << std::endl;}
    ~derived(){std::cout << "~derived" << std::endl;}
    void print(){std::cout << "derived::print" << std::endl;}
};

int main()
{
    std::shared_ptr<base> b_ptr = std::make_shared<derived>();
    b_ptr->print();
    auto d_ptr = std::static_pointer_cast<derived>(b_ptr);
    d_ptr->print();
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读