c++11 学习及测试(shared_ptr, unique_ptr, allocator, function)
2016-03-23 22:38
405 查看
智能指针shared_ptr、unique_ptr,构造及使用,make_sheard<typeName>,可以构造sheard_ptr,但是并没有make_unique。。
函数指针的高端写法 function< reType<argType...> >
#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 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 在 Qt4 中使用 C++11
- c++11新特性--decltype auto
- centos安装devtoolset-3支持gcc 4.9.2
- 使用eclipse编译含有C++11特性的代码
- 怎样在Linux环境编译支持C11
- eclipse支持c++11
- C++11可变参数函数与for循环
- vs2013 编译c++是发现惊天bug
- 简单性能测试函数模板
- 关于C++现状的一些思考
- 用C++11优化矩阵运算的空间和时间效率
- 浅析构造函数之默认构造函数
- c++中返回数组的函数
- C++函数重载的几个问题
- C++11 note-2 字符串 容器 迭代器
- C++11 现代C++风格的新元素
- c++11 lambda表达式浅谈
- C++11之“move”语意
- C++11之Lambda表达式