Destruction of object in local scope

2019-08-13 13:32发布

问题:

Suppose that I have the following code:

void foo() {  
 {
    myclass object;
    object.do_something();
 }
 cout<<"hello"<<endl;
}

Is ~myclass() guaranteed to be called by the time the local scope is exited, or might it be called at a later time (such as when the function returns)?

回答1:

Yes, it is guaranteed:

[class.dtor] Destructors are invoked implicitly for ... a constructed object with automatic storage duration when the block in which the object is created exits.