[英]return by reference/pointer of a static local variable
如果我通過引用獲取靜態unordered_map而不是通過指針獲取靜態unordered_map,為什么會清除它,我感到困惑(您可以在此處執行代碼: http : //cpp.sh/4ondg )
是因為引用超出范圍時會調用其析構函數嗎? 如果是這樣,那么第二個get函數將得到什么呢?
class MyTestClass {
public:
static std::unordered_map<int, int>& getMap() {
static std::unordered_map<int, int> map;
return map;
}
static std::unordered_map<int, int>* getMapByPointer() {
static std::unordered_map<int, int> map;
return ↦
}
};
int main()
{
// By reference
{
auto theMap = MyTestClass::getMap();
std::cout << theMap.size() << std::endl;
theMap[5] = 3;
std::cout << theMap.size() << std::endl;
}
{
auto theMap = MyTestClass::getMap();
std::cout << theMap.size() << std::endl;
theMap[6] = 4;
std::cout << theMap.size() << std::endl;
}
// By pointer
{
auto theMap = MyTestClass::getMapByPointer();
std::cout << theMap->size() << std::endl;
(*theMap)[5] = 3;
std::cout << theMap->size() << std::endl;
}
{
auto theMap = MyTestClass::getMapByPointer();
std::cout << theMap->size() << std::endl;
(*theMap)[6] = 4;
std::cout << theMap->size() << std::endl;
}
}
當你做
auto theMap = MyTestClass::getMap();
推斷theMap
的類型為std::unordered_map<int, int>
–不是引用。 因此,函數調用返回的引用將被復制到局部變量theMap
。 修改theMap
,您僅在修改此副本。
要存儲引用,請將其聲明為auto&
:
auto& theMap = MyTestClass::getMap();
然后,您將按預期修改原始對象。
將靜態地圖分配給本地變量時,無意間將其復制了。 在:
auto theMap = MyTestClass::getMap();
auto
推導為std::unordered_map<int, int>
,而不是std::unordered_map<int, int>&
,這導致新對象從返回的引用中被復制初始化。 因此, theMap
是與靜態地圖完全獨立的對象。
指針版本不存在此問題,因為類型被推導為指針,因此唯一要復制的是指針值本身,該指針值始終指向同一(靜態)對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.