Skip to content

Instantly share code, notes, and snippets.

@junaidrahim
Last active August 19, 2020 08:01
Show Gist options
  • Save junaidrahim/b8685a446e4be528f8ca3edd8b166155 to your computer and use it in GitHub Desktop.
Save junaidrahim/b8685a446e4be528f8ca3edd8b166155 to your computer and use it in GitHub Desktop.
Shared Pointer Example 1
#include <iostream>
#include <memory>
using namespace std;
class SomeBigObject{
public:
float data[1000];
void something() {
// just something
}
void someOtherThing(){
// just some other thing
}
};
void SomeFunction(shared_ptr<SomeBigObject>& p){
shared_ptr<SomeBigObject> p2 = make_shared<SomeBigObject>(); // allocate memory
p = p2; // copy p2 into the pointer passed (ref count = 2)
// p and p2 point at the same object
} // the memory at which p2 points will not be freed here,
// but the ref count will decrement and be 1
int main(){
shared_ptr<SomeBigObject> p1;
SomeFunction(p1);
// the memory allocated by p2 will be freed when the main function ends
p1->something();
p1->someOtherThing();
return 0;
// p1 will go out of scope, ref count will go 0
// and memory will be freed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment