I read the 10 most stupid mistakes to avoid with the C ++ 11 smart pointer . Number 5 reads:
Mistake # 5: Do not assign an object (raw pointer) to shared_ptr as soon as it is created!
int main() { Aircraft* myAircraft = new Aircraft("F-16"); shared_ptr<aircraft> pAircraft(myAircraft); ... shared_ptr<aircraft> p2(myAircraft);
and the recommendation looks something like this:
Use make_shared or new and immediately create a pointer with it.
Well, no doubt, problem and recommendation. However, I have a question about the design of shared_ptr . This is a very simple mistake, and the entire “safe” shared_ptr design can be thrown out with very easy misses.
Now the question is, what can be easily fixed with the alternative design of shared_ptr , in which the only constructor from the raw pointer will be that of the r-value reference?
template<class T> struct shared_ptr{ shared_ptr(T*&& t){...basically current implementation...} shared_ptr(T* t) = delete;
Thus, shared_ptr can only be initialized from the result of new or from some factory function.
Is this a misuse of the C ++ language in the library? or What is the point of having a constructor reference from the original pointer (l-value) if this is most likely to be misused?
Is this a historical disaster? (e.g. shared_ptr was proposed before r-value links, etc., were introduced) Backward compatibility?
(Of course, we can say std::shared_ptr<type>(std::move(ptr)); that it is easier to catch, and also work if it is really necessary.)
Did I miss something?