C Smart Pointers: Advanced Usage and Precautions
Advanced Usage:
1. Custom smart pointers:
You can create your own smart pointers, inherit from std::unique_ptr
or std::shared_ptr
, and customize the behavior for specific needs. .
class CustomPtr : public std::unique_ptr<int> { public: CustomPtr(int* ptr) : std::unique_ptr<int>(ptr) {} ~CustomPtr() { std::cout << "CustomPtr destroyed" << std::endl; } };
2. Convert smart pointers:
You can use the std::make_unique
and std::make_shared
functions to easily Convert between types of smart pointers.
std::unique_ptr<int> up = std::make_unique<int>(42); std::shared_ptr<int> sp = std::make_shared<int>(*up);
3. Circular Reference:
When two smart pointers refer to each other, a circular reference may be created. You can change the type of one of the smart pointers to break the cycle.
struct Node { std::unique_ptr<Node> next; std::shared_ptr<Node> prev; };
Notes:
1. Memory leak:
Forgetting to wrap resources with smart pointers can lead to memory leaks. Make sure to always use smart pointers to manage dynamically allocated memory.
2. Dangling pointers:
Smart pointers may point to deleted objects, resulting in dangling pointers. Avoid checking the validity of smart pointers before using them.
3. Self-looping:
Smart pointers can point to themselves, causing self-looping. Avoid allocating the same object in the constructor of a smart pointer.
4. Performance overhead:
Smart pointers have performance overhead than raw pointers. Use them when needed, such as in complex data structures or when accessing resources across multiple threads.
Practical example:
Consider the following example, which shows how shared pointers prevent dangling pointers:
class Widget { public: std::shared_ptr<Widget> createChild() { return std::make_shared<Widget>(); } }; int main() { std::shared_ptr<Widget> parent = std::make_shared<Widget>(); std::shared_ptr<Widget> child = parent->createChild(); // ... 代码块 1,父对象 parent 被删除 ... // 代码块 2,child 仍然有效 child->doSomething(); return 0; }
In this example, even if the parent objectparent
is removed, child
in block 2 is still valid because std::shared_ptr
maintains shared ownership of the object.
The above is the detailed content of C++ Smart Pointers: Advanced Usage and Considerations. For more information, please follow other related articles on the PHP Chinese website!