Home > Article > Backend Development > How to create a custom pointer in C++?
Custom pointers in C++ are a way to enhance the functionality of standard pointers. Creating a custom pointer includes: 1. Creating a pointer type inherited from std::unique_ptr; 2. Implementing the required functionality in the custom pointer. For example, improve code robustness by creating custom pointers to verify that pointers are null.
In C++, a pointer is a variable that can store the address of another variable. However, sometimes we want to use pointers in a more flexible and robust way, and this is when custom pointers come in handy.
Creating a custom pointer involves the following steps:
std::unique_ptr
Inheritance: template<typename T> class MyPtr: public std::unique_ptr<T> { // 添加自定义功能 };
The following example creates a custom pointer that verifies whether the pointer is null and throws an exception to improve the robustness of the code:
// 创建一个检查非空的自定义指针 template<typename T> class NonNullPtr: public std::unique_ptr<T> { public: NonNullPtr(T* ptr) : std::unique_ptr<T>(ptr) { if (ptr == nullptr) { throw std::invalid_argument("NonNullPtr: Pointer cannot be null"); } } // 其他方法和函数... }; // 使用: int main() { // 创建一个非空的指针 NonNullPtr<int> ptr(new int(5)); // 访问指针指向的值 int value = *ptr; // 尝试创建空指针会导致异常 try { NonNullPtr<int> null_ptr(nullptr); } catch (std::invalid_argument& e) { std::cout << "Caught invalid argument: " << e.what() << std::endl; } return 0; }
The above is the detailed content of How to create a custom pointer in C++?. For more information, please follow other related articles on the PHP Chinese website!