Ugrás a tartalomhoz

Szerkesztő:LinguisticMystic/cpp/SmartPointers

A Wikiszótárból, a nyitott szótárból

📌 Pointers and Their Issues in C++

[szerkesztés]

🔧 What Are Pointers?

[szerkesztés]

Pointers in C++ are variables that store memory addresses. They are extremely powerful for low-level memory manipulation but come with significant risks.

⚠️ Common Pointer Issues

[szerkesztés]
  1. Memory Leaks When you allocate memory using new, you must manually free it using delete. Forgetting to do so causes memory leaks.
  2. Dangling Pointers If you delete a pointer and then use it again, you’re accessing freed memory—this leads to undefined behavior.
  3. Double Deletion Calling delete more than once on the same memory address results in program crashes or corruption.
  4. Manual Cleanup Complexity In large codebases, it’s difficult to ensure every dynamically allocated memory gets properly freed, especially in:
    • Early returns from functions
    • Exceptions being thrown
    • Complex control paths

🔍 Example: Manual Memory Management Pitfalls

[szerkesztés]
#include <iostream>

void processArray(int size) {
    int* arr = new int[size];

    if (size <= 3) {
        return; // Memory leak
    }

    for (int i = 0; i < size; ++i) {
        arr[i] = i;
    }

    if (size > 20) {
        throw std::runtime_error("Array size too large"); // Memory leak
    }

    // Missing: delete[] arr;
}

This function demonstrates:

  • No deletion on early return
  • No cleanup on exception
  • No cleanup at the end of the function



✅ Smart Pointers: The Safe Alternative

[szerkesztés]

📌 What Are Smart Pointers?

[szerkesztés]

Smart pointers are class-based wrappers around raw pointers that automatically manage memory using RAII (Resource Acquisition Is Initialization). When the smart pointer goes out of scope, its destructor is called, which frees the memory safely.

🧠 Types of Smart Pointers in C++

[szerkesztés]
Smart Pointer Description
std::unique_ptr Sole ownership of memory. Automatically deletes memory when it goes out of scope.
std::shared_ptr Shared ownership. Deletes memory when the last reference is destroyed.
std::weak_ptr Non-owning reference to a shared_ptr. Used to avoid cyclic references.



🔐 std::unique_ptr – Exclusive Ownership

[szerkesztés]

✅ Basic Usage

[szerkesztés]
#include <iostream>
#include <memory>

int main() {
    std::unique_ptr<int> ptr(new int(10));
    std::cout << "Value: " << *ptr << std::endl;

    *ptr = 20;
    std::cout << "Modified Value: " << *ptr << std::endl;

    ptr.reset(); // optional manual deletion
    return 0;
}

Key Points:

  • Uses new to allocate an int
  • Automatically deletes memory when ptr goes out of scope
  • reset() is optional but useful if you want to release memory before scope ends

📌 Accessing Raw Pointer

[szerkesztés]
int *rawPtr = ptr.get();
int &ref = *ptr;

🧮 Managing Arrays with std::unique_ptr

[szerkesztés]
#include <iostream>
#include <memory>

int main() {
    std::unique_ptr<int[]> arr(new int[5]{1, 2, 3, 4, 5});
    for (int i = 0; i < 5; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}

🔍 Explanation:

[szerkesztés]
  • std::unique_ptr<int[]> manages a dynamic array.
  • Automatically deletes the array (delete[]) when it goes out of scope.



🧱 Using Smart Pointers with Structs and Classes

[szerkesztés]
#include <iostream>
#include <memory>

struct MyStruct {
    int data;
};

int main() {
    std::unique_ptr<MyStruct> ptr(new MyStruct);
    ptr->data = 42;
    std::cout << "Data: " << ptr->data << std::endl;
}

✅ Arrow Operator (->)

[szerkesztés]

Allows direct access to members of the object being managed, just like a raw pointer.



🛠️ std::make_unique – A Cleaner Way

[szerkesztés]
#include <iostream>
#include <memory>

int main() {
    auto ptr = std::make_unique<int>(42);
    std::cout << "Value: " << *ptr << std::endl;

    *ptr = 99;
    std::cout << "Modified value: " << *ptr << std::endl;
}

📌 Benefits of make_unique

[szerkesztés]
  • Simplifies creation: no need to write new
  • Ensures exception safety
  • Introduced in C++14



✅ Summary

[szerkesztés]
Problem with Raw Pointers Solution via Smart Pointers
Forgetting to delete Automatic cleanup (RAII)
Early return Destructor handles cleanup
Exceptions Memory safely released
Complex code paths Ownership clearly modeled

🏁 Final Thoughts

[szerkesztés]

By adopting std::unique_ptr and other smart pointers, you gain:

  • Safer memory management
  • Cleaner and more maintainable code
  • Fewer runtime bugs and memory leaks

Smart pointers are the modern and recommended way to handle dynamic memory in C++. In new C++ projects, avoid raw new and delete—use smart pointers instead.