#include <iostream>
#include <memory>
#include <string>
#include <map>
#include <functional>
#include <stdio.h>
#include <assert.h>
using namespace std::placeholders;
using namespace std;
class Stock
{
public:
Stock(const string& name) :name_(name)
{
printf("Stock[%p] %s\n", this, name_.c_str());
}
~Stock()
{
printf("~Stock[%p] %s\n", this, name_.c_str());
}
const string& key() const { return name_; }
private:
string name_;
};
class StockFactory :public enable_shared_from_this<StockFactory>
{
public:
StockFactory()
{
printf("StockFactory[%p]\n", this);
}
~StockFactory()
{
printf("~StockFactory[%p]\n", this);
}
shared_ptr<Stock> get(const string& key)
{
shared_ptr<Stock> pStock;
weak_ptr<Stock>& pWeakStock = stocks_[key];
pStock = pWeakStock.lock();
if (!pStock)
{
pStock = shared_ptr<Stock>(new Stock(key), bind(&StockFactory::weakDelCb, weak_ptr<StockFactory>(shared_from_this()), _1));
pWeakStock = pStock;
}
return pStock;
}
private:
static void weakDelCb(const weak_ptr<StockFactory>& factory, Stock* stock)
{
shared_ptr<StockFactory> pFactory(factory.lock());
if (pFactory)
{
pFactory->removeStock(stock);
}
else
{
printf("factory has died\n");
}
delete stock;
}
void removeStock(Stock* pStock)
{
printf("removeStock [%p]\n", pStock);
if (pStock)
{
auto iter = stocks_.find(pStock->key());
if (iter != stocks_.end() && iter->second.expired())
{
stocks_.erase(pStock->key());
}
}
}
private:
map<string, weak_ptr<Stock>> stocks_;
};
void testFactoryLongLife()
{
shared_ptr<StockFactory> factory(new StockFactory);
{
shared_ptr<Stock> stock1 = factory->get("daniel");
shared_ptr<Stock> stock2 = factory->get("daniel");
assert(stock1 == stock2);
}
}
void testFactoryShortLife()
{
shared_ptr<Stock> stock1;
{
shared_ptr<StockFactory> factory(new StockFactory);
stock1 = factory->get("daniel");
shared_ptr<Stock> stock2 = factory->get("daniel");
assert(stock1 == stock2);
}
}
int main(int argc, char **agrv)
{
testFactoryLongLife();
testFactoryShortLife();
system("pause");
return 0;
}
网友评论