简单的数组类 Array

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


template<typename T>
class Array
{
    public:
        Array():data(0),sz(0)
        {
        
        }

        Array(unsigned int size):sz(size),data(new T[size])
        {
        
        }

        ~Array()
        {
            cout<<"Destructor()"<<endl;
            delete []data;
            data=0;
        }

        const T& operator[](unsigned int idx) const
        {
            if(idx>=idx){
                throw out_of_range("Array subscript out fo range const");
            }
            else if(data==0){
                throw out_of_range("data==0 const");
            
            }

            return data[idx];
        }

        T& operator[](unsigned int idx)
        {
            if(idx>=sz){
                throw out_of_range("Array subscript out of range");
            }
            else if(data==0){
                throw out_of_range("data==0");
            }

            return data[idx];
        }

        operator const T* ()const
        {
            return data;
        }

        operator T* ()
        {
            return data;
        }

    private:
        T* data;
        unsigned int sz;

        Array(const Array&);
        Array& operator=(const Array&);
};


#define N 100

int main()
{
   
    /*
    Array<int> t(N);

    for(unsigned int i=0;i<N;i++)
    {
        try{
            t[i] = i;
        }
        catch(...){
            cout<<"error"<<endl;
            exit(-1);
        }
    }

    for(int i=N-1;i>=0;i--)
    {
        try{
            unsigned int idx = (unsigned int)i;
            cout<<t[idx]<<"\t";
        }
        catch(out_of_range e)
        {
            cout<<endl;
            cout<<i<<endl;

            cout<<e.what()<<endl;
            exit(-1);
        }
    }
    cout<<endl;

    int *p = t+10;
    cout<<*p<<endl;
    */

    {
        
        cout<<"=============test=========="<<endl;
        int *pp=0;
        cout<<pp<<endl;


        {
            Array<int> tt(20);
            unsigned x = 10;

            tt[x] = 100;

            pp = &tt[x];
            cout<<*pp<<"\t"<<pp<<endl;   //100   一个地址a
        }

        cout<<*pp<<"\t"<<pp<<endl;   //100   一个地址a
    

        //cout<<tt[x]<<endl;
    }


    return 0;
}

这个里面有个问题和c++沉思录里面所讨论的不一样,就是在后面的测试,感觉很奇怪,求大侠解释。


现象就是:

在没有注释的测试部分,tt当超出作用域的时候,对象已经析构(销毁),但是*pp的输出值任然是100,并且地址也是和之前的一样。。?

个人觉得最后的输出应该是一个不确定的值。。。。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值