Computer Science/C++
[C++] Smart pointers
focalpoint
2023. 9. 30. 00:52
1. unique_ptr
int main() {
auto intPtr{ make_unique<int>(42) };
cout << *intPtr << endl;
}
get() method give access to the internal pointer;
int main() {
auto intPtr{ make_unique<int>(42) };
cout << *intPtr << endl;
cout << *intPtr.get() << endl;
}
unique_ptr also has reset(), release() methods.
2. shared_ptr
unique_ptr does not allow copying; If the pointer needs to be copied from else, use shared_ptr.
int main() {
auto intPtr{ make_shared<int>(42) };
auto copiedPtr{ intPtr };
cout << *copiedPtr << endl;
cout << *copiedPtr.get() << endl;
}