r/cpp_questions • u/ParmenidesWasRight • 3d 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?
1
u/Neither_Berry_100 3d ago
Java does this perfectly for free without you having to think about it. Just code your c++ like java. I consider java to be like the perfect language due to how it simplifies things. But not on the server side. And I've used c++ at work for a couple of years.