Skip to content

Instantly share code, notes, and snippets.

@iarash84
Created March 7, 2023 07:35
Show Gist options
  • Save iarash84/a640c7bbd80832c546b8f5ff21fe5920 to your computer and use it in GitHub Desktop.
Save iarash84/a640c7bbd80832c546b8f5ff21fe5920 to your computer and use it in GitHub Desktop.
shared smart pointer example
#include <memory>
#include <iostream>
class MyClass {
public:
MyClass() {
std::cout << "MyClass constructor called\n"
}
~MyClass() {
std::cout << "MyClass destructor called\n"
}
void foo() {
std::cout << "foo called\n"
}
};
int main() {
std::shared_ptr<MyClass> ptr1(new MyClass());
std::shared_ptr<MyClass> ptr2 = ptr1;
std::cout << "Reference count: " << ptr1.use_count() << std::endl; // Output: "Reference count: 2"
ptr1->foo(); // Output: "foo called"
ptr2.reset();
std::cout << "Reference count: " << ptr1.use_count() << std::endl; // Output: "Reference count: 1"
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment