c++ - Overloading new returns wrong address -
#include <iostream> using namespace std; class station{ int n; float *p; public: station(){}; station(const station &ob){cout<<"copy";} station operator=(station* a){cout<<"nai";} ~station(){cout<<"destructor";} static float counter; friend istream &operator>(istream &stream, station &d); int &getn(){return n;}; float *&getp(){return p;}; void* operator new[](size_t size); void* operator new(size_t size){station *a;a=::new station;return a;}; }; void* station::operator new[](size_t size){ station* a; a=(::new station[size]); int b; b=(size)/(sizeof(station)); for(int i=0;i<b;i++){ cin>a[i]; } cout<<a; return a; } float station::counter; istream &operator>( istream &stream, station &d){ cout<<"dwse arithmo deigmatwn"; int num; stream>>num; d.getp()=new float[num]; d.getn()=num; for(int i=0;i<num;i++){ stream>>d.getp()[i]; } return stream; } int main(){ station* a; a=new station[2]; cout<<a; return 0; }
hello everyone, first post, forgive me mistakes of mine.
i have created new class overload of new operator , extractor. problem address returned new different 1 inside overloaded operator can see in lines cout<<a
stated. however, when erase destructor goes normal. ideas?
when using new[]
operator, compilers can allocate space internal bookkeeping (to store e.g. array size, when calling delete[]
, know how many object destroy). difference see between "raw" allocation , final array allocated object address.
that reason, why should not call delete
on memory allocated via new[]
, vice versa, might result in memory leaks (only fist object destroyed), accessing invalid data and/or freeing bad pointer (technically ub).
edit
as object contents issues, not supposed initialize objects in operator new[]
this
for(int i=0;i<b;i++){ cin>a[i]; }
the operator new/new[] allocate "raw" memory.
simply remove , read object in constructor if wish (the constructors called compiler automatically each object in array), e.g.:
station(){cin >> *this}; // or '>' if want keep
but in general, reading stream done explicitly, can example:
a=new station[2]; for(int i=0;i<2;i++){ cin>a[i]; }
in main()
.
Comments
Post a Comment