- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
#include <mutex>
#include <assert.h>
#include <iostream>
#include <unordered_map>
#include <memory>
#include <string>
#include <stdio.h>
//
// Requirements:
// 1: the bitmap could be used by multiple thread safely.(std::shared_ptr could?)
// 2: cache the bitmap and do not always increase memeory
//@NotThreadSfe
struct Bitmap {
public:
Bitmap(const std::string& filePath) {
filePath_ = filePath;
printf("foo %x ctor %s\n", this, filePath_.c_str());
}
~Bitmap() {
printf("foo %x dtor %s\n", this, filePath_.c_str());
}
std::string filePath_;
};
//@ThreadSafe
struct BitmapCache {
public:
static std::shared_ptr<Bitmap> loadBitmap(const std::string& filePath) {
mutex_.lock();
//whether in the cache
auto iter = cache_.find(filePath);
if (iter != cache_.end()) {
if ((*iter).second) {
return (*iter).second;
} else {
std::shared_ptr<Bitmap> newPtr(new Bitmap(filePath));
(*iter).second = newPtr;
return newPtr;
}
}
//try remove unused elements if possible
if (cache_.size() >= kSlotThreshold) {
std::unordered_map<std::string,std::shared_ptr<Bitmap>>::iterator delIter = cache_.end();
for (auto iter = cache_.begin(); iter != cache_.end(); ++iter) {
auto& item = *iter;
if (item.second && item.second.use_count() == 1) {
delIter = iter;
break;
}
}
if (cache_.end() != delIter) {
(*delIter).second.reset();
cache_.erase(delIter);
}
}
//create new and insert to the cache
std::shared_ptr<Bitmap> newPtr(new Bitmap(filePath));
cache_.insert({filePath, newPtr});
mutex_.unlock();
return newPtr;
}
private:
static const int kSlotThreshold = 20;
static std::mutex mutex_;
static std::unordered_map<std::string,std::shared_ptr<Bitmap>> cache_;
};
/* static */
std::unordered_map<std::string,std::shared_ptr<Bitmap>> BitmapCache::cache_;
/* static */
std::mutex BitmapCache::mutex_;
int main()
{
//test for remove useless element
char buff[200] = {0};
std::vector<std::shared_ptr<Bitmap>> bmpVec(20);
for (int i = 0; i < 20; ++i) {
sprintf_s(buff, 200, "c:\\haha%d.bmp", i);
bmpVec[i] = BitmapCache::loadBitmap(buff);
}
bmpVec[3].reset();
std::shared_ptr<Bitmap> newBmp = BitmapCache::loadBitmap("c:\\new.bmp");
//test for multiple threading...(to be implemenetd)
return 0;
}
我是 C++ 内存管理的新手。您能否给我一个提示:我的方法是否正确,或者我应该采用不同的设计策略或不同的内存管理器策略(例如 weak_ptr 等)?
最佳答案
这让我想起了 Herb Sutter 的 "Favorite C++ 10-Liner"在 GoingNative 2013 上的演讲,稍作改编:
std::shared_ptr<Bitmap> get_bitmap(const std::string & path){
static std::map<std::string, std::weak_ptr<Bitmap>> cache;
static std::mutex m;
std::lock_guard<std::mutex> hold(m);
auto sp = cache[path].lock();
if(!sp) cache[path] = sp = std::make_shared<Bitmap>(path);
return sp;
}
评论:
std::lock_guard
而不是在互斥锁上调用 lock()
和 unlock()
。后者更容易出错并且不是异常安全的。请注意,在您的代码中,前两个 return 语句从未解锁互斥量。weak_ptr
跟踪已分配的位图对象,因此缓存从不 自行保持位图处于事件状态。这消除了手动清理不再使用的对象的需要 - 当引用它们的最后一个 shared_ptr
被销毁时,它们会自动删除。path
以前从未见过,或者相应的 Bitmap
已被删除,cache[path].lock()
将返回一个空 shared_ptr
;下面的 if
语句然后使用 make_shared
加载 Bitmap
,将生成的 shared_ptr
移动分配到 sp
,并设置 cache[path]
以跟踪新创建的位图。path
对应的Bitmap
还活着,那么cache[path].lock()
会创建一个新的 shared_ptr
引用它,然后返回。关于c++ - 如何使用 std::shared_ptr 实现缓存管理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24379786/
使用 shared_ptr 时,我应该只使用 shared_ptr 吗?申报一次或申报shared_ptr无论我经过哪里? 所以在我新建实例的函数中,我将它包装在 shared_ptr 中但是当我从函
#include #include #include using namespace std; struct Node { Node(int data, boost::shared_pt
对于我目前正在处理的代码,我们有时需要使用较旧的编译器在一些较旧的系统上进行编译(例如,我们在较旧的 IBM BlueGene/L 上运行 sims,其支持契约(Contract)规定了一些非常旧的
我正在阅读 this answer作者指的是boost best practices其中说: Avoid using unnamed shared_ptr temporaries to save ty
我正在处理几个类,我想知道如何在我的应用程序类中使用普通成员,而该成员需要使用 shared_from_this()? 这里有一些代码来阐明我的意思(见评论) class Observable { p
我有一个 Foo 类,其中包含一个 Hotel 类 的 shared_ptr,以及一个 Rules 类(位于 namespace Rules 内): class Foo { public: //
我想不通。看起来我遗漏了一些简单的东西?我要在 MakePointToSameValue 中输入什么,以便在点 (1) b.ptr 和c.ptr 与a.ptr 指向同一个 换句话说,a.ptr.get
我已尽我所能制作了 SSCE。我怀疑共享指针在我在 main 中请求它们之前解构(释放)了我的对象。如何在不完全绕过共享指针的情况下防止这种情况发生?这是一个程序中的孤立问题,否则可以通过使用 sha
这个问题在这里已经有了答案: Set shared_ptr with new_pointer that is old_pointer + offset (1 个回答) 关闭 4 年前。 我目前正在学
假设我们有一个类,成员如下 std::map> member_我们无法替换 member通过具有 std::shared_ptr 的 map ,因为该类必须对 ObscureType 的非常量函数进行
我正在用 C++ 做学校作业(我还在学习)。我正在尝试实现随机生成的二叉树结构,使用 shared_ptr 在多个地方存储节点的信息(我需要它作为作业)。考虑以下示例代码(这是我的小测试程序): #i
我有以下类(class) struct Images { std::vector > ptr_vector; } 将 ptr_vector 放入 std::shared_ptr 中不会在复制
我刚刚对一个项目进行了大规模重构,添加了一个基类来代替现在所说基类的派生类(因为我想要这个类的更多“类型”)。 我的问题是,一些实用函数将原始类 A 的引用作为 shared_ptr,因此函数声明如下
我记得 Scott Meyers 教我的 func(shared_ptr(new P), shared_ptr(new Q)); 是危险的,因为(如果我没记错的话)内存分配、引用计数(构造)和分配给
给定 struct X { void f(std::shared_ptr); }; auto x(std::make_shared()); 我大概可以安全地做 x->f(std::move(x
我试着介绍了一些const一些新代码的正确性(实际上是功能范例),发现我无法传递 std::shared_ptr到一个需要 std::shared_ptr 的函数.请注意,我不想放弃 constnes
我需要将原始指针包装到 shared_ptr 中,以便将其传递给函数。该函数在返回后不保留对输入对象的任何引用。 { MyClass i; shared_ptr p(&i); f(p);
我在继承链中有4个类:A-> B-> C,A-> B-> D,其中B是唯一的类模板。 我想拥有一个在id和对象指针(C或D)之间映射的std::map,但是我在将make_shared输出分配给std
boost::shared_ptr 是否解决原始指针问题? Base* p = new Base(); shared_ptr sp(p); shared_ptr sq(p); 两个 shared_
How can shared_ptr be a subclass of shared_ptr? 我想知道如何实现模板类 C这样 C是 C 的子类? 我已经观察到上述情况,例如 shared_ptr和
我是一名优秀的程序员,十分优秀!