C++ How to Convert Raw Pointer to Smart Pointer
std::unique_ptr<T> ptr(rawPtr); for unique ownership or std::shared_ptr<T> ptr(rawPtr); for shared ownership, where rawPtr is your raw pointer.Examples
How to Think About It
std::unique_ptr or shared ownership with std::shared_ptr, then initialize the smart pointer directly with the raw pointer.Algorithm
Code
#include <iostream> #include <memory> int main() { int* rawPtr = new int(42); std::unique_ptr<int> smartPtr(rawPtr); std::cout << "Value: " << *smartPtr << std::endl; // No need to delete rawPtr manually return 0; }
Dry Run
Let's trace converting a raw pointer to std::unique_ptr.
Create raw pointer
rawPtr points to an int with value 42.
Initialize unique_ptr
smartPtr now owns the int pointed by rawPtr.
Access value
*smartPtr returns 42.
| Step | Pointer | Value | Ownership |
|---|---|---|---|
| 1 | rawPtr | 42 | raw pointer owns memory |
| 2 | smartPtr | 42 | unique_ptr owns memory, rawPtr should not be used |
| 3 | smartPtr | 42 | access value via smartPtr |
Why This Works
Step 1: Transfer ownership
Passing the raw pointer to the smart pointer constructor transfers ownership, so the smart pointer manages deletion.
Step 2: Automatic memory management
The smart pointer automatically deletes the object when it goes out of scope, preventing memory leaks.
Step 3: Avoid double deletion
After transferring ownership, do not delete the raw pointer manually to avoid double deletion errors.
Alternative Approaches
#include <memory> int main() { auto ptr = std::make_unique<int>(42); return 0; }
#include <memory> int main() { auto ptr = std::make_shared<int>(42); return 0; }
Complexity: O(1) time, O(1) space
Time Complexity
Creating a smart pointer from a raw pointer is a constant time operation with no loops.
Space Complexity
Smart pointers add a small fixed overhead for control blocks (shared_ptr) or just store the pointer (unique_ptr).
Which Approach is Fastest?
Using std::make_unique or std::make_shared is generally faster and safer than converting raw pointers because they avoid separate allocations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Convert raw pointer to unique_ptr | O(1) | O(1) | When you already have a raw pointer and want unique ownership |
| Convert raw pointer to shared_ptr | O(1) | O(1) | When you already have a raw pointer and want shared ownership |
| Use std::make_unique | O(1) | O(1) | Creating new objects with unique ownership, safer |
| Use std::make_shared | O(1) | O(1) | Creating new objects with shared ownership, more efficient |