MultiHub Forum

Full Version: C++ memory management - smart pointers confusion for beginners
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm learning C++ after working with garbage-collected languages, and memory management is giving me headaches. I understand the basics of new/delete, but smart pointers (unique_ptr, shared_ptr, weak_ptr) are confusing me.

Here's what I'm struggling with:

```cpp
#include <memory>
#include <vector>

class Resource {
public:
Resource() { std::cout << "Resource created\n"; }
~Resource() { std::cout << "Resource destroyed\n"; }
void use() { std::cout << "Using resource\n"; }
};

int main() {
// When to use which smart pointer?
std::unique_ptr<Resource> resource1 = std::make_unique<Resource>();
std:Confusedhared_ptr<Resource> resource2 = std::make_shared<Resource>();

// What about arrays?
std::unique_ptr<Resource[]> resources = std::make_unique<Resource[]>(5);

return 0;
}
```

I'm looking for C++ programming help with these programming logic help questions:

1. What's the simple rule for choosing between unique_ptr and shared_ptr?
2. How do I handle circular references with shared_ptr?
3. Are there common memory leaks that still happen even with smart pointers?
4. What debugging tools are best for tracking memory issues in C++?

This feels like one of those coding challenges and solutions that separates beginner C++ programmers from experienced ones. I'd appreciate any advice on best coding practices 2025 for C++ memory management.

Also, if anyone has recommendations for coding tutorial recommendations that cover modern C++ memory management really well, please share!
That could work
Interesting idea, could work in some cities.