c++pointersdependenciesheap-memory

C++ : avoiding compiler dependencies vs. avoiding pointer overuse


I know it's considered old-fashioned / out-of-date style to overuse pointers where they aren't necessary. However, I'm finding this ideal conflicts with another consideration of avoiding compiler dependencies.

Specifically, I can use forward declarations in a header file and avoid #include statements if member variables are pointers. But then this leads me to member variables of my own classes to be pointers, even when there's not really a good reason to do so.

Incidentally, I find using the Qt framework (which I enjoy) leads me to program in this java-esque everything-on-the-heap programming style since that's the way the interface is setup.

How do I weigh these two competing considerations?


Solution

  • It depends. Reducing dependencies is definitely a good thing, per se, but it must be weighed against all of the other issues. Using the compilation firewall idiom, for example, can move the dependencies out of the header file, at the cost of one allocation.

    As for what QT does: it's a GUI framework, which (usually---I've not looked at QT) means lots of polymorphism, and that most classes have identity, and cannot be copied. In such cases, you usually do have to use dynamic allocation and work with pointers. The rule to avoid pointers mainly concerns objects with value semantics.

    (And by the way, there's nothing "old-fashioned" or "out-of-date" about using too many pointers. It's been the rule since I started using C++, 25 years ago.)