Skip to content

Instantly share code, notes, and snippets.

@vgangireddyin
Last active January 22, 2018 05:45
Show Gist options
  • Save vgangireddyin/9b33380c2de3b11c517985e0083ab1b8 to your computer and use it in GitHub Desktop.
Save vgangireddyin/9b33380c2de3b11c517985e0083ab1b8 to your computer and use it in GitHub Desktop.
class Foo
{
public:
string name;
Foo(string name)
{
this->name = name;
cout << "Foo object with name '" + this->name + "' created." << endl;
}
~Foo()
{
cout << "Foo object with name '" + this->name + "' destroyed." << endl;
}
};
int main()
{
//stack allocation:
{
Foo stack_alloc("stack alloc");
cout << "Execution after object declaration" << endl;
}
//heap allocation:
{
Foo *heap_alloc = new Foo("heap alloc");
delete(heap_alloc);
cout << "Execution after object de-allocation" << endl;
}
return 1;
}
int main()
{
//stack allocation with exception:
try
{
Foo stack_alloc_before_exception("stack alloc before exception");
throw "custome exception";
}
catch(char const*) {}
//heap alloction with exception:
try
{
Foo *heap_alloc_before_exception = new Foo("heap alloc before exception");
throw "custom exception";
delete(heap_alloc_before_exception);
}
catch(char const*) {}
return 1;
}
int main()
{
//smart allocation:
{
SmartPointer sp = SmartPointer(new Foo("smart alloc"));
cout << "Accessing: " << sp.real_pointer-> name << endl;
}
//smart alloc with exception:
try
{
SmartPointer sp = SmartPointer(new Foo("smart alloc before exception"));
cout << "Accessing: " << sp.real_pointer-> name << endl;
throw "custom exception";
}
catch(char const*) {}
return 1;
}
Foo object with name 'stack alloc' created.
Execution after object declaration
Foo object with name 'stack alloc' destroyed.
Foo object with name 'heap alloc' created.
Foo object with name 'heap alloc' destroyed.
Execution after object de-allocation
Foo object with name 'stack alloc before exception' created.
Foo object with name 'stack alloc before exception' destroyed.
Foo object with name 'heap alloc before exception' created.
Foo object with name 'smart alloc' created.
Accessing: smart alloc
Foo object with name 'smart alloc' destroyed.
Foo object with name 'smart alloc before exception' created.
Accessing: smart alloc before exception
Foo object with name 'smart alloc before exception' destroyed.
/*
** Smart wrapper around Foo pointer, which helps to deallocate memory Foo poiner when its moved
** out of scope.
*/
class SmartPointer
{
public:
Foo *real_pointer = NULL;
/*
** Assagin Foo object pointer to real pointer.
*/
SmartPointer(Foo *f)
{
this->real_pointer = f;
}
/*
** Deallocate Foo object before SmartPointer object deallocation.
*/
~SmartPointer()
{
delete(real_pointer);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment