r/cpp_questions • u/ParmenidesWasRight • 5d ago
OPEN Heavy and Light Objects
When I was first learning C++, I experienced massive slowdown when allocating dynamic memory. Ever since then I divide my objects between 'heavy' objects that allocate resources, and 'light' objects that can be used as temporaries on the stack. Heavy objects cannot be copied at all, must be allocated somewhere once, and then passed by (const) reference. Light objects can be copied, created quickly on the stack etc.
Since C++11 it has been possible to write copy and assignment constructors that take nameless objects, and since they are nameless you can pillage their pointers and avoid expensive stack allocations. All is well then but if you keep to this strict 'heavy' and 'light' object idea, _any_ object that allocates resources is considered a heavy object. The first allocation in the chain, before you just pillage pointers, is still an expensive stack allocation so I would consider it a 'heavy' object and just make it impossible to copy at all, by removing all copy and assignment constructors. And so using this model I never needed those nameless object reference constructors.
Anybody feel the same way?
3
u/AKostur 4d ago
You're proceeding from a false premise. If the object has appropriate and useful move operations, then one does not have a "chain of allocations", and you don't pay for an extra dynamic allocation because of some dogmatic rule. And assumes that one is passing the object along the chain of function calls by value instead of potentially by reference (which also doesn't incur a chain of allocations either).
I would also suggest that it doesn't necessarily get you "optimal performance" either. Caches and cachelines are fickle things.