The raw pointer should never be used again.Ĭonsider the following example: int main()Īircraft* myAircraft = new Aircraft("F-16") Mistake # 5 : Not assigning an object(raw pointer) to a shared_ptr as soon as it is created !Īn object should be assigned to a shared_ptr as soon as it is created. Recommendation: Use make_shared to instantiate shared pointers instead of using the raw pointer. So Safety is no longer a concern for this type of usage. In this case, the Aircraft object will not be deleted and will cause memory leak ! After looking at the implementation in MS compiler memory header I found that if the allocation fails, the resource/object is deleted. Safety: Consider the situation where the Aircraft object is created and then for some reason the shared pointer fails to be created. shared_ptr pAircraft = make_shared ("F-16") // Single allocation - FAST !Ģ. On the contrary, when you use make_shared, C++ compiler does a single memory allocation big enough to hold both the manager object and the new object. shared_ptr pAircraft(new Aircraft("F-16")) // Two Dynamic Memory allocations - SLOW !!! Performance : When you create an object with new, and then create a shared_ptr, there are two dynamic memory allocations that happen : one for the object itself from the new, and then a second for the manager object created by the shared_ptr constructor. Make_shared has two distinct advantages over using a raw pointer:ġ. This is pretty safe but don’t forget to retest your code ! □ Mistake # 4 : Not using make_shared to initialize a shared_ptr ! You should do a search and find on your codebase and replace all auto_ptr with unique_ptr. Recommendation – unique_ptr does what auto_ptr was intended to do. I've catalogued them below for easy reference.īefore we begin, let's take a look at a simple Aircraft class we'll use to illustrate the mistakes. However, in the two plus years that I've been using them extensively, I've come across multiple cases where improper use of the C++ 11 smart pointers made the program inefficient or simply crash and burn. In my opinion, it made teaching C++ to newcomers much easier. In many ways, they were a godsent for many folks who hate managing their own memory.
0 Comments
Leave a Reply. |