简体   繁体   中英

Why map::clear doesn't call to the destructor ?

I run to following program , note that the value of the map is a ref (ClassA&) -

#include <iostream>
#include <map>
using namespace std  ; 

class ClassA {
    public :
         ClassA () {    cout<<"Hay ! "<<endl ; }    
        ~ClassA () {    cout<<"Bye ! "<<endl ; }
} ; 

int main () { 
    map< string,ClassA& > myMap ; 
    ClassA a   ; 
    myMap.insert( pair<string,ClassA&>("A",a) ) ; 
    myMap.clear() ; 




}

And get output -

Hay ! 
Bye !

Seems like the myMap.clear() didn't affected cause there is no one more calling to ClassA destructor , can you explain me why ?

Destructor is not called when a reference is deleted. Speaking of which.. I thought maps with references would be illegal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM