Namespaces
Variants
Actions

Talk:cpp/language/scope

From cppreference.com

[edit] Scope and object Lifetime

Below is a proposed code example demonstrating the effect of scope on object lifetime. Modification of current code in the destructor article.

This isn't a comprehensive list, but it does demonstrate the unnoticed side effects of plain old scope brackets.

#include <iostream>
 
struct A
{
    int i;
 
    A ( int i ) : i ( i ) 
    {
        std::cout << "Calling Constructor:\t a" << i << '\n';
    }
 
    ~A()
    {
        std::cout << "Calling Destructor:\t a" << i << '\n';
    }
};
 
A a0(0);                        //In global scope. Construted first, destroyed last
 
void ScopeTest1()
{
    A a1(1);                    //a1 in function scope. Destroyed on exiting function scope                  
    A* p;                       //Pointer only. No object contructed yet.
 
    { // nested scope
        A a2(2);                //a2 in nested scope. Destroyed at end of current scope
 
        {//further nested scope 
            A a3(3);            //a3 Destroyed at end of this scope
        } //a3 out of scope
 
        {//further nested scope
            A a4(4);            //a4 Destroyed at end of this scope
            A a5(5);            //a5 Destroyed at end of this scope
 
        } //a4 out of scope
 
        p = new A(6);           //a5 created on heap. Infinite lifetime until destroyed by call to delete.
 
    } // a2 out of scope
 
    delete p; // calls the destructor of a5
 
} //a1 out of scope. //p out of scope (But a5)
 
void f(){
    std::cout << "Calling f()" << std::endl;
}
 
 
int main(){
 
    ScopeTest1();
 
    std::cout << std::endl;
 
    f(),A(7),f(),f();            //Statement scope. Unnamed instance destroyed at end of statement
 
    A a8(8);
    {
        A& a9 = a8;              //References and pointers fall out of scope
        A* a10 = &a8;            //but underlying object not deleted
    }
 
    return 0;
}

Output:

Calling Constructor:	 a0
Calling Constructor:	 a1
Calling Constructor:	 a2
Calling Constructor:	 a3
Calling Destructor:	 a3
Calling Constructor:	 a4
Calling Constructor:	 a5
Calling Destructor:	 a5
Calling Destructor:	 a4
Calling Constructor:	 a6
Calling Destructor:	 a2
Calling Destructor:	 a6
Calling Destructor:	 a1
 
Calling f()
Calling Constructor:	 a7
Calling f()
Calling f()
Calling Destructor:	 a7
Calling Constructor:	 a8
Calling Destructor:	 a8
Calling Destructor:	 a0

[edit] Link to undefined term

class-head links to Classes but the term doesn't occur there.