Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<cstdio>
- namespace Memory{
- template<class type>
- class counter{
- type** myptr;
- unsigned int *count;
- void countpp(){
- if( count == 0 ) return;
- (*count) ++;
- }
- void countss(){
- if( count == 0 ) return;
- (*count)--;
- if( (*count) == 0 ){
- delete count;
- delete *myptr;
- delete myptr;
- }
- }
- public:
- counter(){
- myptr = 0;
- count = 0;
- }
- counter(type *t){
- myptr = new type*;
- count = new unsigned int;
- *myptr = t;
- (*count) = 1;
- }
- counter( const counter<type> &t ){
- myptr = t.myptr;
- count = t.count;
- countpp();
- }
- ~counter(){
- countss();
- }
- type*& get(){
- return *myptr;
- }
- type*& operator->(){
- return *myptr;
- }
- type& operator*(){
- return **myptr;
- }
- type& operator[](int idx){
- return (*myptr)[idx];
- }
- counter<type>& operator=(counter<type> & t){
- countss();
- myptr = t.myptr;
- count = t.count;
- countpp();
- return *this;
- }
- };
- }
- struct test{
- int garbage[2500000]; //10MB
- };
- typedef Memory::counter<test> TestStruct;
- typedef Memory::counter<int> TestInt;
- int main(){
- {
- TestStruct passback;
- {
- TestStruct bigval(new test);
- for( int i = 0; i < 2500000; ++i )
- bigval->garbage[i] = i;
- passback = bigval;
- }
- printf("%d\n", passback->garbage[533646] );
- getchar();
- }
- printf("The memory should be freed now.\n");
- getchar();
- {
- TestInt passback;
- {
- TestInt bigval(new int[25000000]); //100MB
- for( int i = 0; i < 25000000; ++i )
- bigval[i] = i;
- passback = bigval;
- }
- printf("%d\n", passback[13322646] );
- getchar();
- }
- printf("The memory should be freed now.\n");
- getchar();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement