Tuesday, 9 February 2021

Chapter 19 // Exercise 8, 9 - Principles & Practice Using C++

In this exercise I am using Visual Studio 2017 and a modified version of the std_lib_facilities header found here.

Chapter 19 // Exercise 8

Implement an allocator (section 19.3.7) using the basic allocation functions malloc() and free() (appendix B.11.4). Get vector as defined by the end of section 19.4 to work for a few simple test cases. Hint: Look up "placement new" and "explicit call of destructor" in a complete C++ reference.

Exercise 9

Re-implement vector::operator=() (section 19.2.5) using an allocator (section 19.3.7) for memory managment. (I ended up doing this one automatically as part of 8).

Github: 

I honestly had no clue on this one. It took me a couple of hours of just staring at chapter 19.

I looked up those terms in Bjarne's "The C++ Programming Language 4th ed." and he says that 'explicit calls of destructors should be avoided except in the implementation of resource management classes....However, it would be hard to implement an efficient general container along the lines of the standard-library vector without using explicit destructor calls.'

One very interesting thing I learnt during this exercise is how to detect memory leaks in visual studio when using malloc and free. After I had finished writing my class, I wanted to be absolutely positive that the allocated space was being freed properly so followed this guide to do so:

I then pushed back a few values and exited the program to be greeted with this in the output window:

Interestingly; the destructor for MyVector is not called on exiting main but it is called when MyVector is local to a function. I tested this with a std::vector and it to did not have it's destructor called at the end of main. Now I know for a fact that std::vector will clean up after itself properly so it must mean that this _CrtDumpMemoryLeaks() function dumps the output before MyVector has been destroyed. I'm happy that the class is properly allocating and freeing up memory though when it's local to other functions and I can see it being destroyed.

Then when testing I had a problem with values being destroyed when trying to print. I spent a few hours staring at my screen and eventually went to bed angry. The next day I posted my code and asked for some help in our chat channel at work and my colleagues came to the rescue. Turns out I wasn't actually destroying anything in destroy(). They taught me how to use placement new and call the destructor explicitly.

This exercises took me far longer than I expected but I learnt a ton.

No comments:

Post a Comment