c++11 学习及测试(shared_ptr, unique_ptr, allocator, function)

智能指针shared_ptr、unique_ptr,构造及使用,make_sheard<typeName>,可以构造sheard_ptr,但是并没有make_unique。。

#include <iostream>
#include <vector>
#include <memory>
using namespace std;

class SharedStrings {
public:
    SharedStrings(): _strsPtr(make_shared< vector<string> >()) {
    }
    void push(const string& s) {
        _strsPtr->push_back(s);
    }
    void show() const {
        for_each(_strsPtr->begin(), _strsPtr->end(), [](const string& x){cout << x << endl;});
    }
private:
    shared_ptr< vector<string> > _strsPtr; //公用元素,省空间
};
int main(int argc, char* argv[]) {

    shared_ptr<string> p(new string("wangbing"));
    cout << *p << endl;

    SharedStrings a;
    {
        SharedStrings b;
        b.push("wangbing");
        b.push("WANGBING");
        a = b;
    }
    a.show();

    unique_ptr<int> uniq(new int(42));
    unique_ptr<int> un2(uniq.release());
    //un2.release(); 释放指针所有权,没有被接受,运行期报错
    uniq.reset(un2.release());
    cout << *uniq << endl;
    cout << "Hello world!" << endl;

    return 0;
}
内存管理器allocator,四步走:1,分空间(allocate) 2,构造(construct) 3,析构(destroy) 4,释放空间(deallocate)

#include <iostream>
#include <memory>
using namespace std;

int main(int argc, char* argv[]) {
    allocator<string> alloc;
    int n = 10;
    string* p = alloc.allocate(n);
    string* q = p;
    while(q != p+n) {
        alloc.construct(q++, 10, 'w');
        cout << *(q-1) << endl;
    }
    while(q != p) {
        alloc.destroy(--q);
    }
    alloc.deallocate(p, n);
    cout << "Hello world!" << endl;

    return 0;
}

函数指针的高端写法 function< reType<argType...> >

#include <iostream>
#include <functional>
#include <map>
#include <string>

using namespace std;

class add {
    int operator()(int a, int b) const {
        return a + b;
    }
};

int plu(int a, int b) {
    return a + b;
}

class A {
private:
    int _a = 0;
public:
    A(){}
    explicit A(int a): _a(a) {
    }
    explicit operator bool() const {
        return _a != 0;
    }
    explicit operator int() const {
        return _a;
    }
};

auto divide = [](int a, int b){return a / b;};
int main(int argc, char* argv[]) {
    map<string, function< int(int, int) > > opt{/*{"+", add()},*/
                                                {"+", plu},
                                                {"-", minus<int>()},
                                                {"/", divide},
                                                {"*", [](int a, int b){return a*b;}}};
    cout << opt["+"](8, 4) << endl;
    cout << opt["-"](8, 4) << endl;
    cout << opt["*"](8, 4) << endl;
    cout << opt["/"](8, 4) << endl;
    A a;
    if(a) {
        cout << "wangbing" << endl;
    } else {
        cout << "hehe" << endl;
    }
    int b = static_cast<int>(a) + 10;

    cout << b << endl;
    cout << "Hello world!" << endl;

    return 0;
}



你可能感兴趣的:(C++11)