您的位置:首页 > 编程语言 > C语言/C++

c++11新性能测试2

2014-08-09 19:36 106 查看
#include <iostream>
#include <memory>
#include <cstring>
using namespace std;
struct C {int* data;};
struct D {int a; int b;};
int main()
{
shared_ptr<int> p1;
shared_ptr<int> p2(nullptr);
shared_ptr<int> p3(new int);
shared_ptr<int> p4(new int, default_delete<int>());
shared_ptr<int> p5(new int,[](int *p){delete p;}, allocator<int>());
shared_ptr<int> p6(p5);
shared_ptr<int> p7(move(p6));
shared_ptr<int> p8(unique_ptr<int>(new int));
shared_ptr<C> obj(new C);
shared_ptr<int> p9(obj, obj->data);
cout << "==========test one===========" << endl;
std::cout << "p1: " << p1.use_count() << '\n'; //0
std::cout << "p2: " << p2.use_count() << '\n'; //0
std::cout << "p3: " << p3.use_count() << '\n'; //1
std::cout << "p4: " << p4.use_count() << '\n'; //1
std::cout << "p5: " << p5.use_count() << '\n'; //2
std::cout << "p6: " << p6.use_count() << '\n'; //0
std::cout << "p7: " << p7.use_count() << '\n'; //2
std::cout << "p8: " << p8.use_count() << '\n'; //1
std::cout << "p9: " << p9.use_count() << '\n'; //2
cout << "=============================" << endl;
cout << "==========test two===========" << endl;
int *pInt = new int(10);
shared_ptr<int> p10(pInt);
if(p10.get() == pInt)
cout << " p10 and pInt point to the same location" << endl;
cout << "*p10.get() = " << *p10.get() <<
" *p10 = " << *p10<< " *pInt = " << *pInt << endl; //10 10 10
cout << "=============================" << endl;
cout << "==========test three===========" << endl;
shared_ptr<D> p11;
shared_ptr<D> p12(new D);
p11 = p12;
p11->a = 10;
p12->b = 20;
if(p11) cout << "p11:" << p11->a << " " << p11->b<< endl; //10 20
if(p12) cout << "p12:" << p12->a << " " << p12->b<< endl; //10 20
cout << "p11.unique :" << p11.unique() << endl; //0
cout << "p3.unique :" << p3.unique() << endl; //1
cout << "=============================" << endl;
cout << "==========test three===========" << endl;
shared_ptr<D> p13(new D);
p13->a = 1;
p13->b = 2;
shared_ptr<D> p14(new D);
p14->a = 3;
p14->b = 4;
cout <<"p13:" << p13->a << " " << p13->b << endl; //1 2
cout <<"p14:" << p14->a << " " << p14->b << endl; // 3 4
p13.swap(p14);
cout << " After swap:" << endl;
cout <<"p13:" << p13->a << " " << p13->b << endl; //3 4
cout <<"p14:" << p14->a << " " << p14->b << endl; // 1 2
D d = *p13;
cout << "d:" << d.a << " " << d.b <<endl;
cout << "=============================" << endl;
char *p = new char[100];
shared_ptr<char> sp(p);
strcpy(sp.get(), "Hello,world");
cout << "*sp.get() = " << sp.get() << endl;
cout << "p = " << p << endl;
strcpy(p, "I am a test!");
cout << "*sp.get() = " << sp.get() << endl;
cout << "p = " << p << endl;
//通过shared_ptr 管理指针,通过原始指针访问内存
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: