2016-12-15 10 views
1

静的な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 &map; 
    } 

}; 


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; 
    } 
} 
+0

'std :: unordered_map * j =&(getMap())' - どのオブジェクトが 'j'を指しているのか想像してみてください。 –

+0

'auto theMap = MyTestClass :: getMap();'はマップのコピーを作成します。参照を安全にするには 'auto&'を使います。 [Live](http://melpon.org/wandbox/permlink/L5T1zSXriVZw138P) –

+2

もう一度魂、 'auto'キーワードでヒット – Stargateur

答えて

5

theMapのタイプはstd::unordered_map<int, int>なると推定されます。したがって、関数呼び出しによって返される参照はtheMapコピーされます。 theMapを変更すると、このコピーのみが変更されます。

auto&としてそれを宣言し、参照を格納するには、次の

auto& theMap = MyTestClass::getMap(); 

意図したとおりに、あなたは、元のオブジェクトを変更することがあります。

+0

あなたはそれを修正する方法を説明したのでプラス1つ:D – Cameron

+0

、非常に素晴らしい説明! –

1

静的マップをローカル変数に割り当てたときに意図せずにコピーしています。で:

auto theMap = MyTestClass::getMap(); 

autoは、返された参照からコピー、初期化する新しいオブジェクトを起こしstd::unordered_map<int, int>、ないstd::unordered_map<int, int>&、と推定されます。したがって、theMapは静的マップとは完全に別のオブジェクトです。

ポインタの型がポインタに導かれるため、ポインターのバージョンにはこの問題はありません。したがって、コピーされるのはポインタ値自体であり、常に同じ(静的な)オブジェクトを指します。

関連する問題