Last active
March 30, 2021 02:12
-
-
Save tklee1975/685068397786cdc6b56049d050d1885b to your computer and use it in GitHub Desktop.
Study C++ Object life cycle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <iostream> | |
#include <memory> | |
#include <vector> | |
struct Tracer { // ken: from book 'C++ Crash course' Page 97 | |
private: | |
const char* const _name; // const xxx const mean cannot alter both address and content | |
public: | |
Tracer(const char *name) | |
: _name{name} { | |
cout << name << " is constructed\n"; | |
} | |
~Tracer() { | |
cout << _name << " is destructed\n"; | |
} | |
}; | |
void pause() { | |
cout << "Paused! press enter to continue\n"; | |
cin.ignore(); // Ref: https://stackoverflow.com/questions/903221/press-enter-to-continue | |
} | |
void testObjectCycle() { | |
Tracer tracer("Tracer 1"); | |
std::vector<unique_ptr<Tracer>> tracerList1; | |
std::vector<shared_ptr<Tracer>> tracerList2; | |
// | |
// pause(); | |
cout << "\nCreate an object inside a block scope\n"; | |
{ | |
Tracer tracerInBlock("Tracer in Block"); | |
} // tracerInBlock is destructed here | |
cout << "\nCreate an object pointer inside a block scope\n"; | |
{ | |
Tracer *trackerPtr = new Tracer("Tracer Raw Pointer"); | |
} // trackerPtr not destructed here.. it is dangerous | |
cout << "\nCreate an unqiue pointer inside a block scope\n"; | |
{ | |
unique_ptr<Tracer> uPtr = make_unique<Tracer>("Tracer Unique Pointer"); | |
//tracerList1.push_back(std::move(uPtr)); // this line make the sPtr destructed after pause | |
} // Cool, unique_ptr can be clean up when the block is ended | |
cout << "\nCreate an shared pointer inside a block scope\n"; | |
{ | |
shared_ptr<Tracer> sPtr = make_shared<Tracer>("Tracer Shared Pointer"); | |
//tracerList2.push_back(sPtr); // this line make the sPtr destructed after pause | |
} // Cool, shared_ptr can be clean up when the block is ended | |
pause(); | |
cout << "Program End\n"; | |
} | |
int main(int argc, char **argv) | |
{ | |
testObjectCycle(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment