#include <vector>
#include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;
struct Foo{
Foo(int _x) : x(_x){}
~Foo()
{
cout << "~Foo()" << endl;
}
int x;
};
struct FooPtrOps{
void operator() (const FooPtr & a)
{
std::cout << a->x << endl;
}
bool operator()(const FooPtr & a, const FooPtr & b)
{
return a->x > b->x;
}
};
bool Sooorrt(const FooPtr & a, const FooPtr & b)
{
return a->x < b->x;
}
typedef boost::shared_ptr<Foo> FooPtr;
class Shared
{
public:
Shared()
{
std::cout << "ctor() called" << std::endl;
}
Shared(const Shared & other)
{
std::cout << "copy ctor() called" << std::endl;
}
~Shared()
{
std::cout << "dtor() called" << std::endl;
}
Shared & operator = (const Shared & other)
{
std::cout << "operator = called" << std::endl;
}
};
int main(int argc, char *argv[])
{
vector<FooPtr> foo_vector;
foo_vector.resize(10);
FooPtr foo_ptr(new Foo(2));
foo_vector.push_back(foo_ptr);
auto sadsa = foo_vector[0].get();
if (!foo_vector[0])
{
cout << "kong" << endl;
}
if (!sadsa)
{
cout << "kong" << endl;
}
sadsa = foo_vector[10].get();
if (sadsa)
{
cout << "bukong " << endl;
}
if (foo_vector[10])
{
cout << "bukong" << endl;
}
foo_vector[0].reset(new Foo(2));
sadsa = foo_vector[0].get();
cout << sadsa->x << endl;
foo_ptr.reset(new Foo(1));
foo_vector[1] = foo_ptr;
foo_ptr.reset(new Foo(4));
foo_vector[2] = foo_ptr;
foo_ptr.reset(new Foo(3));
foo_vector[3] = foo_ptr;
foo_ptr.reset(new Foo(4));
foo_vector.push_back(foo_ptr);
cout << "foo_vector" << endl;
for_each(foo_vector.begin(), foo_vector.begin() + 4, FooPtrOps());// 2143
cout << "foo_set" << endl;
cout << "降序" << endl;
std::sort(foo_vector.begin(), foo_vector.begin() + 4, FooPtrOps());
for_each(foo_vector.begin(), foo_vector.begin() + 4, FooPtrOps());// 4321
cout << "升序" << endl;
std::sort(foo_vector.begin(), foo_vector.begin() + 4, Sooorrt);
for_each(foo_vector.begin(), foo_vector.begin() + 4, FooPtrOps());// 1234
//cout << "foo_vector" << endl;
//for_each(foo_vector.begin(), foo_vector.end(), FooPtrOps());// 下标4中 指针为空,所以蹦了
//cout << "foo_set" << endl;
typedef std::vector<Shared> VShared1;
VShared1 v1;
v1.push_back(Shared());//1.ctor() called 2.copy ctor() called 3.dtor() called
v1.clear(); //4.dtor() called
// 智能指针
typedef boost::shared_ptr<Shared> SharedSP;
typedef std::vector<SharedSP> VShared;
VShared v;
v.push_back(SharedSP(new Shared()));//ctor() called
v.push_back(SharedSP(new Shared()));//ctor() called
SharedSP a = v.front();// 引用v.front对应的指针
{
Shared b = *a;// copy ctor() called
}//dtor() called
v.clear();// 释放v.back()对应内存,应为存在引用SharedSP a = v.front();所以只打印一句dtor() called
return 0;
}