#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;
}
弱回调示例
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- springboot整合redis这里就省略,可以参考之前写过的一篇:springboot连接redis[http...
- 前言 网络框架 本文一开始上传图片以调用HYNetworking的API为例,这个网络框架是以AFNetworki...
- 目录 参考 示例说明 示例代码 1. 参考 [1] FFmpeg/doc/examples/avio_readin...