I was watching a lecture by Bjarne Stroustrup from 2014, on "The Essence of C++". About halfway through he rather forcefully recommends not using new, delete, or pointers for class member data, but rather delegating that work entirely to container objects (i.e., from the STL) whenever possible. For example, he shows the following slide example at 43:18:
Now, as part of exercise for the courses in C++ that I teach, I happen to maintain my own Matrix class (which gets used in a WeightedGraph class for data storage as an adjacency matrix), and of course I use a pointer to an array of ints, a
new in the constructor, and a
delete in the destructor. So I considered looking at what it would take to covert this to Stroustrup-approved style, using a
Two things occur to me that look ugly to my eye. First, and most important, I think in the constructor to my Matrix class -- at the point when I know what the fixed size of the matrix will be -- I won't be calling the vector's constructor, but rather the function
elem.resize(). (Right?) That is: I "know" that this is the moment when memory allocation will occur, but I "write" as though I'm unaware of that, and there's some existing data that I'm modifying. Second, somewhat less important, the destructor in my Matrix class will be empty (I think?), and likewise for I guess every class I write going forward. So (at least pedagogically) we just start forgetting that destructors are a thing and that resources need cleaning-up.
In turn, consider my WeightedGraph class that stores its data in an adjacency Matrix. Again, I currently have a pointer to a Matrix that gets allocated in the constructor and cleaned up in the destructor. Now if I follow this same model and give it a non-pointer Matrix for member data, I need to go add a similar
resize() function to the Matrix, and basically all of its current constructors (one for a square matrix, one for rectangular, etc.) become useless. And this methodology flows to whatever classes further aggregate our classes so far. Both constructors and destructors become hidden, and we're always pretending to be "resizing" objects when really we know we're allocating memory for the one and only time.
Am I correct about this advice from Stroustrup? Is there any more expressive way of using this advice to clearly reflect that we know we're doing one-off allocation in the constructors of these objects?