Should we avoid assignment of derived types in robust programs?

A huge share of C++ literature is related to explaining the semantics of construction, copying, assignment, moving, and destruction. Two “safe” idioms they have come up with are:

Given that Fortran lacks the concept of object construction entirely, and the result of overloading the structure constructor will always need pass through an assignment, for derived types which contain pointer components initialization by a subroutine seems to be safest option. The same then goes for copying, or moving an object, in a fashion similar to the rule of three.

It seems like the C++ community had just began to learn all the hard-lessons on safe OO programming, roughly at the same time OO features were added to the Fortran standard.

As a slight tangent, I’m wondering if one extra-level of indirection can help, meaning you wrap the pointer in another derived type, nested in the consumer one. This would be akin to the smart pointers like std::unique_ptr or std::shared_ptr. I believe a comment from @rouson posted in a stdlib issue is relevant to this discussion:

A decade ago, when I worked on the Trilinos project, which already surpassed a million lines of code back then, contributors were forbidden from using raw pointers and this was a C++ project so that was a pretty radical position at the time. Contributors were required to use a reference-counted pointer template class instead — effectively what these days would be called a smart pointer. Fortran’s allocatable variables are our smart pointers. Whenever they can be used, I recommend using them over pointers in every case. There are so many subtle ways to get things wrong in hard-to-debug ways with pointers that I’ll avoid using a library that has pointers under the hood if I can possibly avoid it. I recently abandoned a library that was exhibiting strange behaviors that I couldn’t diagnose and was using pointers. You can’t just think about whether the code works now. Think about what happens when a naive new developer comes into a project, not knowing the best practices to keep the code safe from runtime errors. I basically won’t believe the correctness of any non-trivial code that uses pointers if that code doesn’t encapsulate the pointers in a way that guarantees automated reference-counting and if the project doesn’t enforce a policy that only the encapsulated form of reference-counted pointer ever be used in the project.

1 Like