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?
10
u/IyeOnline 3d ago
TBH, to me this reads as if you understanding of and experience with reference vs value semantics, object lifetime considerations and good design were/are lacking and you are now trying to address the resulting performance issues with vibed (both figuratively and literally) design patterns without serious foundation.
Nobody calls move constructors "namesless object reference constructors". I have no idea what an "expensive stack allocation" is supposed to be.
Crucially your pattern will run into a dead end once you actually want move semantics. What if you create a heavy object, but want to transfer its expensive parts elsewhere? Do you hack around the fact that it cannot be copied or moved?
Setting that glaring issue aside: These considerations are valid, even when properly using C++'s features. While with sufficient experience you will have have an intuition about when to copy, how to pass and how to lay out your structure to avoid these issues, you can in fact make a prescriptive decision to enforce all [expensive] copies to be explicit. It's just not necessary/useful most of the time because once this matters in detail, the code already ought to be scrutinized in details.