放入地图时 std::string 的范围
Scope of std::string when put in map
我是 C++ 领域的新手,对 std::string
插入到 std::map
.
的生命周期有点困惑
例如:
void loadMap(std::map<string, int> &myMap)
{
int num = rand();
myMap[to_string(num) + "_xyz"] = num;
}
void main(int argc, char** argv)
{
std::map<string, int> myMap;
loadMap(myMap);
//Is the entry I just added to the map in loadMap still safe in there?
//i.e., is the key, which is an std::string, still around?
//Or its lifetime's ended?
}
我做了一些测试,SEEMS 没问题,但我不确定是否会一直如此。也许我很幸运,std::string 所在的内存没有被触及。
以下操作将创建一个 std::string
右值
to_string(num) + "_xyz"
由于 map
的 Key
类型是 std::string
by value 那么这个右值将有效地移动到映射中。在这种情况下你是安全的。现在映射 "owns" 那个字符串。因此,字符串的生命周期与 main
中映射的生命周期相同
别担心,地图是安全的,所有条目都有有效值。
如果您查看 std::map::operator[]
,您会发现密钥必须是:
CopyConstructible
如果该密钥的 key/value 对不存在(and/or 密钥无法移动)
MoveConstructible
如果密钥可以移动,无需复制
这是有原因的:容器会复制(或移动)密钥来存储它。如果密钥不存在,它将不会存储指针或引用。
值也是如此:它是对已存储在地图中的值的引用,因此当您这样做时
myMap[to_string(num) + "_xyz"] = num;
您正在将 num
复制到容器的内部值。
我是 C++ 领域的新手,对 std::string
插入到 std::map
.
例如:
void loadMap(std::map<string, int> &myMap)
{
int num = rand();
myMap[to_string(num) + "_xyz"] = num;
}
void main(int argc, char** argv)
{
std::map<string, int> myMap;
loadMap(myMap);
//Is the entry I just added to the map in loadMap still safe in there?
//i.e., is the key, which is an std::string, still around?
//Or its lifetime's ended?
}
我做了一些测试,SEEMS 没问题,但我不确定是否会一直如此。也许我很幸运,std::string 所在的内存没有被触及。
以下操作将创建一个 std::string
右值
to_string(num) + "_xyz"
由于 map
的 Key
类型是 std::string
by value 那么这个右值将有效地移动到映射中。在这种情况下你是安全的。现在映射 "owns" 那个字符串。因此,字符串的生命周期与 main
别担心,地图是安全的,所有条目都有有效值。
如果您查看 std::map::operator[]
,您会发现密钥必须是:
CopyConstructible
如果该密钥的 key/value 对不存在(and/or 密钥无法移动)MoveConstructible
如果密钥可以移动,无需复制
这是有原因的:容器会复制(或移动)密钥来存储它。如果密钥不存在,它将不会存储指针或引用。
值也是如此:它是对已存储在地图中的值的引用,因此当您这样做时
myMap[to_string(num) + "_xyz"] = num;
您正在将 num
复制到容器的内部值。