C++ Smart Pointers
Smart pointers are objects that behave like pointers but provide automatic memory management. They automatically deallocate memory when it is no longer needed, avoiding memory leaks. C++ offers three types of smart pointers: unique_ptr, shared_ptr, and weak_ptr. Here's an example using unique_ptr:
#include <iostream>
#include <memory>
int main() {
// Creating a unique_ptr
std::unique_ptr<int> myPtr = std::make_unique<int>(42);
// Accessing the value
std::cout << "Value: " << *myPtr << std::endl;
// Modifying the value
*myPtr = 100;
// Releasing the ownership
myPtr.release();
return 0;
}
In the above code, we create a unique_ptr named myPtr that points to an int with a value of 42. We access the value using the dereference operator * and modify it. Finally, we release the ownership of the pointer using the release() function.
No comments:
Post a Comment