#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,并且地址也是和之前的一样。。?
个人觉得最后的输出应该是一个不确定的值。。。。