Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions Object Lifetime-(stack $ scope lifetimes)/Log.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#include <iostream>
#include <string>

class Entity
{
public :
Entity()
{
std::cout << "Created Entity!" << std::endl;
}

~Entity()
{
std::cout << "Destroyed Entity!" << std::endl;
}
};

class ScopedPtr
{
private :
Entity* m_Ptr;
public :
ScopedPtr(Entity* Ptr)
: m_Ptr(Ptr)
{
}

~ScopedPtr()
{
delete m_Ptr;
}

};




int main()
{


{

ScopedPtr e = new Entity();//we can also write it in constructor way and it is implicit conversion
Entity* e = new Entity(); //upper code allocated on heap and get destroyed after the scope ends ,scopedptr object allocated on stack!
}


std::cin.get();
}


// we can write unq ptr which is a scoped ptr but now lets write in a simple class
// timer class for benchmarking and mutex locking[multiple threads cant access at sametime locks and unlocks after ] are examples of this type of using scopedptrs'
49 changes: 49 additions & 0 deletions Object Lifetime-(stack $ scope lifetimes)/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#include <iostream>
#include <string>

class Entity
{
public :
Entity()
{
std::cout << "Created Entity!" << std::endl;
}

~Entity()
{
std::cout << "Destroyed Entity!" << std::endl;
}
};

int* CreateArray(int* array)
{

int* array = new int[50];//Heap allocation
//int array[50];//stack allocated
return array;//returning ptr in stack memory
}

int main()
{

int array[50];//copying memory
int* a = CreateArray(array);

{
//Entity e;

Entity* e = new Entity();
}


std::cin.get();
}



// {} THIS IS A SCOPE!! WE HAVE SCOPES FOR CLASSES,EMPTY CLASSES AND FOR IF STATEMENTS!
// JUST DEBUG THE CODE AND VERIFY EACH LINE
// WHILE STACK OR SCOPE ALLOCATION AFTER SCOPE ENDS IT DOES DESTROYS ENTITY
// WHILE HEAP ALLOCATION IT DOES LIVES EVEN AFTER SCOPE ENDS
// BY USING "Scoped ptr" OR SCOPE CLASSES AND UNQ PTR WHICH IS A SMART POINTER WE CAN ALLOCATE ON HEAP AND AUTO DELETE THE MEMORY AFTER SCOPE ENDS
// A CLASS THATS A WRAPPER OVER A POINTER WHICH UPON CONSTRUCTION HEAP ALLOCATES THE POINTER AND THEN UPON DESTRUCTION DELETES THE POINTER
1 change: 1 addition & 0 deletions this--keyword/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,4 @@ int main()
}


//IN Const methods this is a const entity constant pointer!!