Welcome to the lesson on C++'s auto_ptr! This deprecated smart pointer is a powerful tool in managing memory. Let's dive in!
auto_ptr is a class template provided by C++ to handle dynamic memory allocation. It acts as a wrapper for a pointer and manages the memory deallocation automatically.
auto_ptr holds a raw pointer and manages its lifetime.auto_ptr object is destroyed or assigned to another auto_ptr, the deallocation of the managed object is automatically handled.#include <memory>
std::auto_ptr<type> var_name = new type;Replace type with the data type you want to allocate memory for and var_name with the variable name.
#include <iostream>
#include <memory>
int main() {
std::auto_ptr<int> myInt(new int(10));
std::cout << *myInt << std::endl; // Output: 10
std::auto_ptr<int> anotherInt = myInt; // Deallocation happens automatically
std::cout << *anotherInt << std::endl; // Output: 10
return 0;
}Let's say we have a class MyClass that manages a resource.
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() {
std::cout << "Creating MyClass object.\n";
// Resource allocation here
}
~MyClass() {
std::cout << "Deleting MyClass object.\n";
// Resource deallocation here
}
};
int main() {
std::auto_ptr<MyClass> myObj(new MyClass);
std::auto_ptr<MyClass> anotherObj = myObj; // Deallocation happens automatically
return 0;
}Since C++11, auto_ptr has been deprecated in favor of std::unique_ptr and std::shared_ptr. However, understanding auto_ptr is still valuable for learning smart pointers in C++.
What is the purpose of C++'s `auto_ptr`?