Skip to content

Instantly share code, notes, and snippets.

@pvrs12
Created April 18, 2018 15:51
Show Gist options
  • Save pvrs12/1028ecc053b7572dafd02979696be750 to your computer and use it in GitHub Desktop.
Save pvrs12/1028ecc053b7572dafd02979696be750 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <memory>
void test_unique() {
std::unique_ptr<int> foo = std::make_unique<int>(4);
std::cout<<*foo<<std::endl;
//std::unique_ptr<int> bar = foo;
}
void test_shared() {
{
std::shared_ptr<int> foo = std::make_shared<int>(9);
std::cout<<*foo<<std::endl; //prints 9
std::shared_ptr<int> bar = foo; //increases the reference counter to 2
foo = nullptr; //decreases the reference counter to 1
(*bar)++; // increments the value in bar
std::cout<<*bar<<std::endl; //prints 10
}
//when bar goes out of scope the memory is freed and the pointer deleted
}
void test_weak() {
std::weak_ptr<int> weak;
{
std::shared_ptr<int> foo = std::make_shared<int>(-2);
weak = foo; //does not increase the reference counter
//in order to use the weak pointer it must be copied into a shared pointer
if (std::shared_ptr<int> bar = weak.lock()) { //this increases the reference coutner to 2
std::cout<<*bar<<std::endl;
} else { // and leaving scope decreases it to 1
std::cout<<"The pointer is expired"<<std::endl;
}
}
if (std::shared_ptr<int> bar = weak.lock()) { // the shared pointer is expired at this point
std::cout<<*bar<<std::endl;
} else {
//so this occurs
std::cout<<"The pointer is expired"<<std::endl;
}
}
int main() {
std::cout<<"Unique Pointers"<<std::endl;
test_unique();
std::cout<<"Shared Pointers"<<std::endl;
test_shared();
std::cout<<"Weak Pointers"<<std::endl;
test_weak();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment