静的なunordered_mapが参照によって取得された場合、なぜそれがクリアされるのか混乱しますが、ポインタで取得できない場合は...(ここでコードを実行することができます:http://cpp.sh/4ondg )参照先/静的ローカル変数のポインタ
参照が範囲外になると、そのデストラクタが呼び出されるのでしょうか?もしそうなら、2番目のget関数は何を得ますか?ない参照 - あなたは
auto theMap = MyTestClass::getMap();
を行うと
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;
}
}
'std :: unordered_map * j =&(getMap())' - どのオブジェクトが 'j'を指しているのか想像してみてください。 –
'auto theMap = MyTestClass :: getMap();'はマップのコピーを作成します。参照を安全にするには 'auto&'を使います。 [Live](http://melpon.org/wandbox/permlink/L5T1zSXriVZw138P) –
もう一度魂、 'auto'キーワードでヒット – Stargateur