2y ago · May 14, 2024 11:30 AM
Modern C++ emphasizes **RAII (Resource Acquisition Is Initialization)**. In intermediate and production codebases, manual and should be replaced with smart pointers.
1. (Zero Overhead Ownership)
- Exclusive ownership model. Cannot be copied, only moved.
- Has zero memory or CPU runtime overhead compared to a raw pointer.
- Always prefer:
---
2. (Reference Counted Ownership)
- Multiple shared pointers can own the same object.
- Maintains an atomic control block tracking reference count ().
- Deletes resource when reference count reaches 0.
---
3. (Breaking Circular References)
- Observes a without incrementing the reference count.
- Prevents memory leaks caused by cyclic dependencies (e.g. Node A pointing to Node B, and Node B pointing back to Node A).
CODE
new CODE
delete1.
CODE
std::unique_ptr<T>- Exclusive ownership model. Cannot be copied, only moved.
- Has zero memory or CPU runtime overhead compared to a raw pointer.
- Always prefer
CPP
std::make_unique<T>() CPP
#include <memory>
#include <iostream>
struct Texture {
int width, height;
Texture(int w, int h) : width(w), height(h) {}
void Bind() { std::cout << "Texture bound: " << width << "x" << height << "
"; }
};
void ProcessTexture() {
auto tex = std::make_unique<Texture>(1920, 1080);
tex->Bind();
// Memory is automatically released when tex goes out of scope!
}---
2.
CODE
std::shared_ptr<T>- Multiple shared pointers can own the same object.
- Maintains an atomic control block tracking reference count (
CODE
use_count- Deletes resource when reference count reaches 0.
CPP
auto sharedTex = std::make_shared<Texture>(512, 512);
std::cout << "Ref count: " << sharedTex.use_count() << "
"; // 1
{
auto alias = sharedTex;
std::cout << "Ref count inside scope: " << sharedTex.use_count() << "
"; // 2
}
std::cout << "Ref count after scope: " << sharedTex.use_count() << "
"; // 1---
3.
CODE
std::weak_ptr<T>- Observes a
CODE
std::shared_ptr- Prevents memory leaks caused by cyclic dependencies (e.g. Node A pointing to Node B, and Node B pointing back to Node A).
CPP
std::weak_ptr<Texture> weakTex = sharedTex;
if (auto locked = weakTex.lock()) { // Safely convert to shared_ptr if object is still alive
locked->Bind();
} else {
std::cout << "Texture was destroyed
";
}
VectorByte | DirectX 11/12 Hooking & ImGui Overlays
Quote
Math is the language of game engines.
The following users thanked VectorByte for this post: