包含范围外对象地址的地图是否未定义行为?

Is a map containing addresses of out-of-scope objects undefined behavior?

如果我有对象地址到其他类型的映射,例如字符串:

std::map<unsigned long, std::string> index;
//       ^^^ This is a number representing address of an object
//       that may go out of scope while the map is still alive.

是否向其推送对象 使用指向可能在映射之前超出范围的对象的地址,未定义的行为?请注意,我只是读取地址,而不是通过映射修改寻址对象。

假设 stringstd::string,它不是地址。 unsigned long 也不是地址。

如果您将一些指针值转换为 unsigned long 并将该 unsigned long 用作映射中的键,则读取这些整数没有问题。它们与原始指针没有隐式关系。

您的问题是:

Is pushing to it objects that may go out of scope before the map, undefined behavior?

我的回答假设“推送”是指向地图添加或插入元素。在下面的代码示例中,我们将对象(对)添加到超出内部范围的地图中,但即使这样访问地图也是有效的,因为对象已复制到地图中。

#include <iostream>
#include <map>

int main()
{
    std::map<unsigned long, std::string> index;
    
    {//new scope started

    //create some objects to insert into the map inside this new scope
    std::pair<unsigned long, std::string> pair1(4, "String1");
    std::pair<unsigned long, std::string> pair2(5, "String2");
    std::pair<unsigned long, std::string> pair3(6, "String3");
    
    //add these objects into the map 
    index.insert(pair1);//pair1 is copied into the map so you dont have to worry about pair1 going out of scope
    index.insert(pair2);//pair2 is copied
    index.insert(pair3);//pair3 is copied as well
    
    }//pair1, pair2 and pair3 goes out of scope after this point
    
    std::cout<<index.at(4)<<std::endl;//this is ok because all the pair objects were copied into the map so you don't have to worry about them going out of scope 
    return 0;
}

因此,对象 (std::pair) 在我们将它们插入地图后将超出范围。但是我们仍然可以使用地图,因为那些 pair 被复制到了地图中。所以把可能超出作用域的元素插入map之前就可以了

Is pushing to it objects that may go out of scope before the map, undefined behavior?

没有

请注意(正如其他人所提到的)您的地图不包含外部对象的地址,而是对象的副本(副本将有自己的生命周期,无关到原来的)。

指针映射为:

std::map<unsigned long, std::string*> index;