Are there any problems with the mayor during his implementation?
Here is one: you cannot take responsibility for the link. The whole point of a smart pointer is to claim ownership of the pointer itself. shared_ref cannot work because you cannot control the link lifetime.
And no, that won't fly either:
shared_ref( T&& ref ) : p(&ref) {}
The user may have given you a stack variable, which now means that you have "joint" ownership between this object and the stack variable. And stack variables cannot share ownership of something.
You can control the pointer lifetime. And pointers can be NULL. So the only thing you can do is check the runtime to see if the pointer is NULL.
Absolutely the best you can do is an interface equivalent to shared_ptr , except that it does not have a default constructor and is thrown if NULL is provided. Is it really worth creating a new pointer type?
The C ++ Fundamentals Support Library has a not_null pattern that can be applied to most types like pointers. That way, you can use not_null<shared_ptr> when you want to check that the pointer is not NULL, but only once when it enters use. After the pointer is first created, it does not need to be checked again.
Of course, you cannot force other people to use them, but using this type will solve the problem one by one.
source share