保证我的指针内存容器稍后存在

Guaranteeing my container of pointers memory exists later?

本文关键字:存在 内存 我的 指针      更新时间:2023-10-16

我有一些这样的代码:

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的地图是更好的选择。