Created
February 6, 2015 07:21
-
-
Save madduci/0357475192af9c6158f1 to your computer and use it in GitHub Desktop.
Modern C++ - Memory
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 <iostream> | |
#include <memory> | |
void classic_cpp() | |
{ | |
std::cout << "***Classic C++***" << std::endl; | |
/*Classic C++*/ | |
int *x = new int(10); | |
std::cout << "value of x: " << *x << " ---- address of x: " << x << std::endl; | |
*x = 100; | |
std::cout << "value of x: " << *x << " ---- address of x: " << x << std::endl; | |
delete x; | |
x = NULL; | |
x = new int[10]; //reusage of same variable name | |
x[0] = 2; | |
x[9] = 11; | |
std::cout << "value of x[0]: " << x[0] << " ---- address of x[9]: " << x[9] << std::endl; | |
delete[] x; //without deleting the x, i have a memory leak | |
x = NULL; | |
} | |
void modern_cpp() | |
{ | |
std::cout << "***Modern C++***" << std::endl; | |
/*Modern C++*/ | |
std::unique_ptr<int> x(new int(10)); | |
std::cout << "value of x: " << *x << " ---- address of x: " << x.get() << std::endl; | |
*x = 100; | |
std::cout << "value of x: " << *x << " ---- address of x: " << x.get() << std::endl; | |
x.reset(new int[10]); //reusage of same variable name | |
x.get()[0] = 2; | |
x.get()[9] = 11; | |
std::cout << "value of x[0]: " << x.get()[0] << " ---- address of x[9]: " << x.get()[9] << std::endl; | |
} | |
int main() | |
{ | |
classic_cpp(); | |
modern_cpp(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment