
//
// This is example code from Chapter 18.3.1 "Debugging constructors and destructors" of
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//

#include "std_lib_facilities.h"

//------------------------------------------------------------------------------

struct X {    // simple test class
    int val;

    void out(const string& s)
    { cerr << this <<  "->" << s << ": " << val << "\n"; }

    X() : val(0) {  ///default constructor
        out("X()");
        ///val=0;
    }
    X(int v) : val(v) { ///construct an X with a value
        out( "X{int}");
        ///val=v;
    }
    X(const X& x) : val(x.val) { ///construct an X that copies an X
        val=x.val;
        out("X{X&} ");
        ///val=x.val;
    }
    X& operator=(const X& a) {
        out("X::operator=()");
        val=a.val;
        return *this;
    }
    ~X() { out("~X()"); }
};

//------------------------------------------------------------------------------

X glob(2);            /// a global variable

X copy(X a) { return a; } ///define copy() without ref

X copy2(X a) { X aa = a; return aa; }///copy without ref after making copy with "="


X& ref_to(X& a) { return a; }  ///copy by reference

X* make(int i) { X a{i}; return new X(a); }

struct XX {
    X a;
    X b;
};

//------------------------------------------------------------------------------

int main()
{
    X loc{4};        // local variable
    X loc2 = loc;
    cin.get();

    loc = X(5);
    loc2 = copy(loc); ///X copy(X a) { return a; }
    cin.get();cin.get();cin.get();
    cin.get();cin.get();cin.get();

    loc2 = copy2(loc); ///X copy2(X a) { X aa = a; return aa; }
    X loc3(6);
    cin.get();

    X& r = ref_to(loc3);  ///X& ref_to(X& a) { return a; }
    delete make(7);  ///X* make(int i) { X a{i}; return new X(a); }
    delete make(8);
    cin.get();

    vector<X> v(4);
    XX loc4;
    cin.get();

    X* p = new X{9};    // an X on the free store
    delete p;
    cin.get();

    X* pp = new X[5];    // an array of Xs on the free store
    delete[] pp;
}

//------------------------------------------------------------------------------

















