保证我的指针内存容器稍后存在
Guaranteeing my container of pointers memory exists later?
我有一些这样的代码:
typedef std::unordered_map<int, A*> MAP;
MAP _map;
int myMethod(){
B b;
const int key = 4;
addToMap(key, b);
}
void addToMap(const int i, B& b){
MAP::accessor a;
_map.insert(a, MAP::value_type(I, &b));
}
我担心一旦返回myMethod()
堆栈上创建的B
对象将不存在于我的地图中。我也不能轻易更改MAP的界面,因为它在很多地方使用。
我该怎么做才能addToMap()
,以保证我的 map 元素在返回后不会被删除myMethod()
?
我可以强制插入 B 的副本吗?
我想B
提供了一个复制构造函数。
因此:
- 您无法修改
typedef std::unordered_map<int, A*> MAP;
- 您的实际地图应该拥有其指针指向的对象,
-
B
继承自A
(这可以解释为什么原始代码的作者在MAP
中使用指针)
您可以使用此代码:
// it's useless to pass an int by reference,
// and you should pass b by const ref
void addToMap(int i, const B& b){
auto old = _map[i]; // if _map[i] doesn't exist, insert nullptr,
// if it does, return old value.
delete old; // if old doesn't exist, old == nullptr
_map[i] = new B(b);
}
当(且仅当)B(const B& b)
不抛出时,这段代码很好。如果是这样,_map
将包含一个无效值 (nullptr),但不会泄漏任何内存。
但是,在其他方法中应小心谨慎,以便在从地图中移除地图所指向的对象时正确销毁这些对象。此外,您应该销毁封闭对象(持有地图的对象)的析构函数中的剩余对象。
最后,如果可以的话,您应该遵循建议,这些建议说您可以使用unique_ptr
。如果您的遗留代码在所有权问题上设计不佳,也许带有shared_ptr
的地图是更好的选择。
相关文章:
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 为什么以下C++代码中存在内存泄漏?
- 以下代码是否存在内存泄漏?
- 存在内存访问异常,但我不确定我的代码中出了什么问题
- gpc服务器不会释放内存,是否存在内存泄漏?
- 存在内存泄漏问题的链接列表
- QT图像查看器示例,可能存在内存泄漏
- 为什么堆栈中的函数局部变量之间存在内存空间
- C :当居民记忆缓慢增加时,是否存在内存泄漏
- 是否存在内存泄漏,如果是,为什么?
- 如果函数返回 std::vector<std::string>,是否存在内存泄漏?
- 检测到指针引用可能存在内存泄漏
- 是否可能存在内存泄漏以在堆上分配shared_ptr
- 在这个关于指针的C++代码示例中是否存在内存泄漏
- 是否存在内存泄漏
- 尽管释放了分配的内存,但仍存在内存泄漏
- 复制构造函数中存在内存泄漏
- 优先级队列中可能存在内存泄漏
- C++中非常大的数组存在内存问题
- 如果我将一个POD结构分配给另一个POD组织,是否存在内存泄漏